angular.module('starter.shop', [])
    .controller('shoPreviewCtrl', function ($scope, $timeout, $faAPI, $authorize, $stateParams, $faUser, $rootScope, $state, $faPlatform, $faUtil, $interval, $lfShare, $location,$faPopup, $filter,$chatToken,$ionicPopup, $ionicHistory, $window, $ionicSideMenuDelegate, $faCookies) {
        try {
            //if (window.localStorage.getItem("startpage") == null) {
            //    //判断是否已经展示过启动页，如果未展示过则跳转APP引导页
            //    //$state.go('app')
            //    $rootScope.modal.startpage();
            //    return;
            //}
            $scope.baseUrl = reqUrl;
            $scope.isShopme = true;

            // if($faUtil.localStorage.get('user') && $faUtil.localStorage.get('user').isLogin) {
            //     $faUser.update();
            // }

            if ($stateParams.sphone) {
                $scope.phone = $stateParams.sphone;
                $scope.isShopme = false;
            } else {
                if($faUtil.localStorage.get("user")!=undefined) {
                    $scope.phone = $faUtil.localStorage.get("user").mobile;
                    window.localStorage.setItem("rankPhone", $faUtil.localStorage.get("user").mobile);//达人秀
                }
            }

            //进入首页埋点统计
            function btnShareStatis() {

                var reqData = {
                    type: '110409',
                    host: $location.host(),
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP',
                    shopId: $scope.phone,
                    userId: $faUser.info.mobile

                };
                $faAPI.shops.statis({
                    type: 'statisitics',
                    data: reqData
                }).then(function (json) {
                });
            }
            btnShareStatis();

            if ($faUser.info == undefined) {
                $faUser.info.isLogin = false;
            }

            //判断用户是否登录
            if ($scope.phone) {

                //请求预约金额数据
                $faAPI.appointment.dayMoney().then(function(respons){

                    $scope.thisData = respons.view;
                    //console.log($scope.thisData);

                })

                initData();
            } else {

                $faUser.info = {
                    isLogin: false,
                    mobile: $faUser.info.mobile
                };

                $faUtil.localStorage.remove('user');

                $rootScope.modal.login(function () {
                    //登录回调
                    $faUtil.localStorage('user', $faUser.info);
                    $scope.phone = $faUser.info.mobile;

                    //请求预约金额数据
                    $faAPI.appointment.dayMoney().then(function(respons){

                        $scope.thisData = respons.view;

                    })

                    $faUser.info.isLogin = true;

                    initData()
                });
            }

            // var uRole;
            //已登录 - 初始化查询
            function initData() {
                //获取店铺主人信息
                $faAPI.shops.shopUserInfo({
                    loginName: $scope.phone
                }).then(function (json) {
                    console.info(json)
                    $scope.user = json.dto;
                    $scope.shopperUserInfoDto = json.shopperUserInfoDto;

                    if (json.shopperUserInfoDto.userName) {
                        $rootScope.shopUserName = json.shopperUserInfoDto.userName;
                    } else {
                        $rootScope.shopUserName = json.dto.uRealName
                    }

                    // uRole = json.dto.role;

                    $rootScope.shopUserPhone = json.dto.loginName;
                    $rootScope.shopUserImg = json.shopperUserInfoDto.userHeadImg;

                    $scope.shopYxtFunction = json.shopYxtFunction;//英雄帖功能显示开关
                    $rootScope.shopYxtAd = json.shopYxtAd;//英雄帖广告显示开关

                    initShare();
                    if ($scope.user.userWechatDto && $scope.user.userWechatDto.headimgurl) {
                        $scope.user.uImage = $scope.user.userWechatDto.headimgurl;
                    }
                });
            }

            function initShare() {
                //分享信息
                var name = $scope.shopperUserInfoDto.shopperName ? $scope.shopperUserInfoDto.shopperName : '我的店铺';
                var desc = $scope.shopperUserInfoDto.shopperDesc ? $scope.shopperUserInfoDto.shopperDesc : '想找好的产品，想看独到的见解就来我的店铺吧!';
                var img_url;
                if ($scope.shopperUserInfoDto.userHeadImg) {
                    if ($scope.shopperUserInfoDto.userHeadImg.indexOf("http") > -1) {
                        img_url = $scope.shopperUserInfoDto.userHeadImg;
                    } else {
                        img_url = reqUrl + $scope.shopperUserInfoDto.userHeadImg + '?x-oss-process=image/resize,m_fill,h_100,w_100';
                    }
                } else {
                    img_url = 'http://lec.superfa.cn/upload/bann/20161208/1481164249317854085.png';
                }
                var shareData = {
                    title: name,
                    desc: desc,
                    link: $location.protocol() + '://' + $location.host() + '/#/shopPreview?sphone=' + $scope.phone,
                    imgUrl: img_url

                };

                //分享
                $scope.proshare = function () {

                    //APP分享统计
                    btnshareShop();

                    shareData.link = reqUrl + '/#/shopPreview?sphone=' + $faUser.info.mobile;
                    console.log(shareData);
                    if ($faPlatform.androidAPP) {
                        document.addEventListener("deviceready", OnDeviceReady, false);
                        function OnDeviceReady() {
                            cordova.exec(null, null, "MyPlugin", "toActivityShare", [shareData.title, shareData.desc, shareData.link, shareData.imgUrl]);
                        }
                    } else {

                        actionShare(shareData.title, shareData.desc, shareData.link, shareData.imgUrl);
                    }
                };
            }

            //点击分享按钮统计
            function btnshareShop() {

                var reqData = {
                    type: '110408',
                    host: $location.host(),
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP',
                    shopId: $scope.phone,
                    userId: $faUser.info.mobile
                };
                $faAPI.shops.statis({
                    type: 'statisitics',
                    data: reqData
                }).then(function (json) {
                });
            }

            //h5端检查未读
            //$faAPI.shops.ryToken().then(function (data) {
            {
                setTimeout(function() {
                    console.info($chatToken.getter())
                    if($chatToken.getter()) {
                        //初始化
                        var userInfo = {
                            appKey: CHAT_APPKEY,
                            token: $chatToken.getter()
                        };
                        $chatToken.setter($chatToken.getter());
                        $chatToken.setter_img($chatToken.getter_img);
                        console.log('检查未读');
                        //公有云初始化
                        RongIMLib.RongIMClient.init(CHAT_APPKEY);
                        //instance = RongIMClient.getInstance();

                        //此接口必须在init()方法之后，连接融云服务器 connect 之前调用。
                        RongIMClient.getInstance().hasRemoteUnreadMessages($chatToken.getter(), {
                            onSuccess: function (hasMessage) {
                                if (hasMessage) {
                                    // 有未读的消息
                                    console.log('是否有未读消息');
                                    console.log(hasMessage);
                                    $scope.hasMessage = true;
                                    // $rootScope.isNewsCome = true;

                                } else {
                                    // 没有未读的消息
                                    console.log('是否有未读消息');
                                    console.log(hasMessage);
                                    $scope.hasMessage = false;
                                    // $rootScope.isNewsCome = false;
                                }
                            }, onError: function (err) {
                                // 错误处理...
                                console.log('获取未读消息错误');
                                $scope.hasMessage = false;
                                // $rootScope.isNewsCome = false;
                            }
                        });
                    }
                }, 2000);
            }

            //});

            $scope.userLoginout = function () {
                $ionicSideMenuDelegate.toggleLeft(false);

                $faUtil.localStorage.remove('_token');

                $faUtil.cookie.remove('_token', {
                    path: '/'
                });

                $faAPI.user.logout().then(function () {

                    console.info($faUser.info.mobile)
                    $faUser.info = {
                        isLogin: false,
                        mobile: null
                    };

                    $faUtil.localStorage.remove('user');
                    $faUtil.localStorage('user', $faUser.info);

                    $rootScope.userRole = null;

                    // $faUser.update();
                    var currouter = $location.path();
                    if(currouter.indexOf('shopHome')<0) {
                        $state.go('shopHome');
                    }
                    $rootScope.modal.login(function(){
                        //登录回调
                        $scope.phone = $faUser.info.mobile;

                        //请求预约金额数据
                        $faAPI.appointment.dayMoney().then(function(respons){

                            $scope.thisData = respons.view;

                        })

                        $faUser.info.isLogin = true;
                        initData();
                    });

                });
            }

            //消息通知
            $scope.goInform = function(){

                //$faUser.info.isLogin ? $state.go('inform') : $rootScope.modal.login();
                $state.go('inform');
            };
            //关闭侧栏菜单
            $scope.toggLeft = function() {
                $ionicSideMenuDelegate.toggleLeft();
                $timeout(function(){
                    if($faPlatform.IOSAPP) {
                        //IOS拨打电话
                        phonedialer.dial("02131038770", function(err) {
                            if (err == "feature")
                                console.info("Your device doesn't support this feature.");
                            if (err == "empty")
                                console.info("Unknown phone number");
                        });
                    } else {
                        //ANDROID拨打电话
                        window.location.href="tel:02131038770";
                    }

                },300)
            };
            //消息统计
            {
                $rootScope.ddzt = {};
                if($faUser.info && $faUser.info.isLogin) {
                    $faAPI.inform.ddtz().then(function (json) {
                        $rootScope.ddzt = json;
                        console.info(json.jPushShopCount)
                        //if(json.jPushShopCount) {
                        //    alert(12)
                        if (parseInt(json.jPushShopCount) > 0) {
                            $rootScope.isHaveShopnews = true;
                        } else {
                            $rootScope.isHaveShopnews = false;
                        }
                        //}
                    });
                }
            }
            //to 产品管理
            $scope.gotoProduct2 = function(){
                $rootScope.isExitProAdd = true;
                $rootScope.count_statis_btnAndPage('110402', 'app.shopsProduct2', $scope.phone, null, null);
            }
            $rootScope.pupclos = true;
            $scope.pupclose = function(){
                $rootScope.pupclos = false;
                $rootScope.isshowac = false;
            }

            //广告跳转
            function getCookie(c_name)
            {
                if (document.cookie.length>0)
                {
                    var c_start=document.cookie.indexOf(c_name + "=")
                    if (c_start!=-1)
                    {
                        c_start=c_start + c_name.length+1
                        var c_end=document.cookie.indexOf(";",c_start)
                        if (c_end==-1) c_end=document.cookie.length
                        return unescape(document.cookie.substring(c_start,c_end))
                    }
                }
                return ""
            }

            $scope.toM = function () {
                $faAPI.user.info().then(function (json) {//用户认证状态更新
                    var uRole = json.user.uRole;
                    if(uRole) {
                        if(uRole != '98' && uRole != '99' && uRole != '1') {
                            //调用原生方法跳转 - 英雄帖活动，用户已经认证过
                            if (!ISWEB) {
                                if ($faPlatform.IOSAPP) {
                                    var url = 'http://'+domainname+'/yxtact/app/#/yxtHome/ios/1?refereePhone='+json.user.uLoginName;
                                    Briefing("理财师英雄帖", url, null, null)
                                }else if ($faPlatform.androidAPP) {
                                    var url = 'http://'+domainname+'/yxtact/app/#/yxtHome/android/1?refereePhone='+json.user.uLoginName;
                                    document.addEventListener("deviceready", OnDeviceReady, false);
                                    function OnDeviceReady() {
                                        cordova.exec(null, null, "MyPlugin", "jianbao", ["理财师英雄帖",null, null, url]);
                                    }
                                }
                            }
                        } else {//英雄帖活动，用户未认证
                            if (!ISWEB) {
                                //认证 - 答题
                                if ($faPlatform.IOSAPP) {
                                    var token = $window.encodeURIComponent(json.token);
                                    var url = 'http://' + domainname + '/yxtact/app/#/yxtAuth/' + json.user.uLoginName + '?fromTo=ios&token='+token+"&ptsource=1";
                                    Briefing("理财师身份认证", url, null, null)
                                } else if ($faPlatform.androidAPP) {
                                    var token = $window.encodeURIComponent(json.token);
                                    var url = 'http://' + domainname + '/yxtact/app/#/yxtAuth/' + json.user.uLoginName + '?fromTo=android&token='+token+"&ptsource=1";
                                    document.addEventListener("deviceready", OnDeviceReady, false);

                                    function OnDeviceReady() {
                                        cordova.exec(null, null, "MyPlugin", "jianbao", ["理财师身份认证",null, null, url]);
                                    }
                                }
                            }
                        }
                    }
                })
            }

            //盟跳转
            $scope.toMeng = function () {
                if (!ISWEB) {
                    if ($faPlatform.IOSAPP) {
                        var url = 'http://'+domainname+'/yxtact/app/#/yxtList/'+$rootScope.shopUserPhone+"?fromTo=ios";
                        Briefing("拉好友得奖金", url, null, null)
                    }else if ($faPlatform.androidAPP) {
                        var url = 'http://'+domainname+'/yxtact/app/#/yxtList/'+$rootScope.shopUserPhone+"?fromTo=android";
                        document.addEventListener("deviceready", OnDeviceReady, false);
                        function OnDeviceReady() {
                            cordova.exec(null, null, "MyPlugin", "jianbao", ["拉好友得奖金", null, null ,url]);
                        }
                    }
                }
            }

            //用于其他地方登录后更新用户的登录认证状态--2017/12/13
            window.isprolistUpdate = function(){
                $faAPI.user.info().then(function (json) {//用户认证状态更新
                    $rootScope.curUserRole = json.user.uRole;
                })
                $rootScope.isshowac = false;
            };
        } catch(e) {
            alert(e)
        }

    })
//店铺预览
    .controller('shopIndexCtrl', function ($scope, $faAPI, $authorize, $stateParams, $faUser, $rootScope, $state, $faPlatform, $faUtil, $interval, $lfShare, $location,$faPopup, $filter,$chatToken,$ionicPopup) {
        //var mySwiper = new Swiper('.swiper-shoppreview .swiper-container', {
        //    direction: 'horizontal',
        //    initialSlide: 0,
        //    // 如果需要分页器
        //    pagination: '.swiper-pagination',
        //    observer: true,//修改swiper自己或子元素时，自动初始化swiper
        //    observeParents: true//修改swiper的父元素时，自动初始化swiper
        //})

        var isFromZixun = $stateParams.isFromZixun;
        $scope.isFromZixun = isFromZixun;

        $scope.baseUrl = reqUrl;
        //$scope.baseUrl = 'http://wap5.superfa.cn';
        $scope.isShopme = true;
        $faUser.update();
        var phone;
        if ($stateParams.sphone) {
            phone =  $scope.phone = $stateParams.sphone;
            $scope.isShopme = false;
        } else {
            phone = $scope.phone = $faUser.info.mobile;
            //$scope.phone = '18911111111';
        }
        $scope.ismaster = $stateParams.ismaster;

        $faAPI.shops.ShopViewCount({
            shopId: $scope.phone
        }).then(function (json) {
            $scope.shopCount = json;
        });

        //通过参数判断，如果是分享进入统计请求
        function shopStatis() {

            var reqData = {
                type: '110100',
                host: $location.host(),
                path: $location.path(),
                param: $location.search(),
                source: 'WAP',
                shopId: $stateParams.sphone

            };
            $faAPI.shops.statis({
                type: 'statisitics',
                data: reqData
            }).then(function (json) {
            });
        }

        //h5微信分享成功后的统计
        function h5shareStatis() {

            var reqData = {
                type: '110400',
                host: $location.host(),
                path: $location.path(),
                param: $location.search(),
                source: 'WAP',
                shopId: $scope.phone,
                userId: $faUser.info.mobile

            };
            $faAPI.shops.statis({
                type: 'statisitics',
                data: reqData
            }).then(function (json) {
            });
        }

        window.shareCallBack = function () {
            h5shareStatis();
        }
        function getshopUserSaySay(){
            //获取动态
            $faAPI.shops.shopUserSaySay({
                loginName: $scope.phone,
                pageSize: 5,
                pageNo: 1
            }).then(function (json) {
                $scope.saylist = json.list;
                console.log("图片=========：")
                console.log(json.list)

                for(var i=0;i<$scope.saylist.length;i++){
                    //$scope.saylist[i].simages  =  $scope.saylist[i].simages.substring(0, $scope.saylist[i].simages.length).split(',')

                    var simages = $scope.saylist[i].simages;
                    if(simages.substring(0,1) == ",") {
                        $scope.saylist[i].simages  = simages.substring(1,simages.length).split(',')
                    } else {
                        $scope.saylist[i].simages  = simages.split(',')
                    }

                }

                console.log(json.list)

                console.log('动态');
                console.log($scope.saylist);
                $scope.pager = json.pager;
            });
        }

        //判断是否是微信环境
        var isWeiXin =function(){
            var ua = window.navigator.userAgent.toLowerCase();
            if(ua.match(/MicroMessenger/i) == 'micromessenger'){
                return true;
            }else{
                return false;
            }
        }
        console.info("店铺主："+$scope.phone)
        if($scope.phone){
            //获取店铺主人信息
            $faAPI.shops.shopUserInfo({
                loginName: $scope.phone
            }).then(function (json) {
                $scope.user = json.dto;
                $scope.shopperUserInfoDto = json.shopperUserInfoDto;
                //是否分享
                console.info("is微信环境："+isWeiXin())
                if(isWeiXin()) {
                    console.info("微信环境：===")
                    if ($stateParams.sphone) {
                        //是否微信授权
                        console.info("微信wechatId："+json.wechatId)
                        if (!json.wechatId) {
                            $authorize.maAuth(shopStatis);
                        } else {
                            shopStatis();
                        }
                    }
                }
                initShare();
                if ($scope.user.userWechatDto && $scope.user.userWechatDto.headimgurl) {
                    $scope.user.uImage = $scope.user.userWechatDto.headimgurl;
                }
            });
            getshopUserSaySay();
            //获取店铺产品信息
            $faAPI.shops.list({
                pageSize: 5,
                pageNo: 1,
                loginName: $scope.phone,
                productState:1
                // loginName:'18221039646',
            }).then(function (json) {
                $scope.shoproducts = json.list.map(function (item) {
                    if (item.fpFundInfoDTO) {
                        item.fpFundInfoDTO.lsjzJson = item.fpFundInfoDTO.lsjzJson ? $faUtil.fromJson((item.fpFundInfoDTO.lsjzJson).replace(/“/g, '"')) : '';
                    } else if (item.productDTO) {
                        if (item.productDTO.expectSaleAmount != 0) {
                            item.productDTO.process = ((item.productDTO.allSubscriptionAmount * 100 / item.productDTO.expectSaleAmount).toFixed(2) > 100) ?
                                100 :
                                (item.productDTO.allSubscriptionAmount * 100 / item.productDTO.expectSaleAmount).toFixed(2);
                        } else {
                            item.productDTO.process = 0;
                        }
                    }
                    return item;
                });
                $scope.shoproductsPager = json.pager;
            });
        }else {
            console.log($scope.phone);
            console.log($faUser.info);
        }

        $scope.shopsActivity = [];
        $scope.shopsActivityPage = [];
        $faAPI.shops.activityList({pageSize: 2, pageNo: 1, mobile: $scope.phone}).then(function (json) {
            if (json) {
                $scope.shopsActivity = json.list;

                angular.forEach($scope.shopsActivity, function (o, i) {
                    if (o.activityEndDate) {
                        var ttime = $filter("date")(o.activityEndDateTime, "yyyy/MM/dd HH:mm");
                        if ((new Date(ttime)) > (new Date())) {
                            o.activityOver = false;
                        } else {
                            o.activityOver = true;
                        }
                    }
                });

                $scope.shopsActivityPage = json.pager;
            }
        });

        $scope.toView = function (type, id) {
            if (type && id) {
                var url = '';

                if (type == '01') {
                    url = 'product.simu';
                } else if (type == '02' || type == '03' || type == '07') {
                    url = 'product.shopxtzgdetail';
                } else if (type == '06') {
                    url = 'product.shoppevc';
                }
                if($scope.isShopme){
                    $state.go(url, {id: id});
                }else {
                    $state.go(url, {id: id, share: 'true', sharePhone: $scope.phone});
                }

            } else {
                console.log('error,,');
            }

        };
        function initShare(){
            //分享信息
            var name = $scope.shopperUserInfoDto.shopperName?$scope.shopperUserInfoDto.shopperName:'我的店铺';
            var desc = $scope.shopperUserInfoDto.shopperDesc?$scope.shopperUserInfoDto.shopperDesc:'想找好的产品，想看独到的见解就来我的店铺吧!';
            var img_url;
            if($scope.shopperUserInfoDto.userHeadImg){
                if($scope.shopperUserInfoDto.userHeadImg.indexOf("http")>-1){
                    img_url=$scope.shopperUserInfoDto.userHeadImg;
                }else{
                    img_url = reqUrl+ $scope.shopperUserInfoDto.userHeadImg+'?x-oss-process=image/resize,m_fill,h_100,w_100';
                }
            }else {
                img_url = 'http://lec.superfa.cn/upload/bann/20161208/1481164249317854085.png';
            }
            var shareData = {
                title: name,
                desc: desc,
                link: $location.protocol() + '://' + $location.host() + '/#/shopPreview?sphone=' + $scope.phone,
                imgUrl: img_url

            };

            //微信分享
            $lfShare.wechatShare(shareData, h5shareStatis);

            //店铺预览分享按钮统计
            function btnsharePreview() {

                var reqData = {
                    type: '110504',
                    host: $location.host(),
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP',
                    shopId: $scope.phone,
                    userId: $faUser.info.mobile

                };
                $faAPI.shops.statis({
                    type: 'statisitics',
                    data: reqData
                }).then(function (json) {
                });
            }

            //分享
            $scope.proshare = function () {
                // 分享统计
                btnsharePreview()
                shareData.link = reqUrl + '/#/shopPreview?sphone=' + $faUser.info.mobile;
                console.log(shareData);
                if ($faPlatform.androidAPP) {
                    h5shareStatis();
                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        cordova.exec(null, null, "MyPlugin", "toActivityShare", [shareData.title, shareData.desc, shareData.link, shareData.imgUrl]);
                    }
                } else {

                    actionShare(shareData.title, shareData.desc, shareData.link, shareData.imgUrl);
                }
                //APP分享统计
                //h5shareStatis();
            };
        }




        //h5端检查未读
        $faAPI.shops.ryToken().then(function(data){
            //初始化
            var userInfo = {
                appKey: CHAT_APPKEY,
                token: data.token
            };
            $chatToken.setter(data.token);
            $chatToken.setter_img(data.portraitUri);
            console.log('检查未读');
            //公有云初始化
            RongIMLib.RongIMClient.init(CHAT_APPKEY);
            //instance = RongIMClient.getInstance();

            //此接口必须在init()方法之后，连接融云服务器 connect 之前调用。
            RongIMClient.getInstance().hasRemoteUnreadMessages(data.token,{
                onSuccess:function(hasMessage){
                    if(hasMessage){
                        // 有未读的消息
                        console.log('是否有未读消息');
                        console.log(hasMessage);
                        $scope.hasMessage = true;

                    }else{
                        // 没有未读的消息
                        console.log('是否有未读消息');
                        console.log(hasMessage);
                        $scope.hasMessage = false;
                    }
                },onError:function(err){
                    // 错误处理...
                    console.log('获取未读消息错误');
                    $scope.hasMessage = false;
                }
            });


        });
        //if($faPlatform.IOSAPP){
        //$faAPI.shops.ryToken().then(function(data){
        //    //初始化
        //    loginRongyun(data.token);
        //});
        if($faPlatform.IOSAPP){
            $scope.goshophomeIOS = function(){
                mychatlist();
            }
        }
        if($faPlatform.androidAPP){
            $scope.goshophomeIOS = function(){
                document.addEventListener("deviceready", OnDeviceReady, false);
                function OnDeviceReady() {
                    cordova.exec(null, null, "MyPlugin", "mychatlist", []);
                }
            }
        }

        //$scope.toView = function (type, id) {
        //    if (type && id) {
        //        var url = '';
        //
        //        if (type == '01') {
        //            url = 'product.simu';
        //        } else if (type == '02' || type == '03' || type == '07') {
        //            url = 'product.shopxtzgdetail';
        //        } else if (type == '06') {
        //            url = 'product.shoppevc';
        //        }
        //        if(!$stateParams.sphone){
        //            $state.go(url, {id: id});
        //        }else {
        //            $state.go(url, {id: id, share: 'true', sharePhone: $scope.sphone});
        //        }
        //
        //    } else {
        //        console.log('error,,');
        //    }
        //
        //};
        $scope.product2godetail = function(proSource,type,id,myid){
            //id平台产品code,自有产品id
            if(proSource == 'self'){
                if(!$stateParams.sphone){
                    $state.go('myProduct2Detail', {id: myid});
                }else {
                    $state.go('myProduct2Detail', {id: myid, share: 'true', sharePhone: $scope.phone});
                }

            }else {
                $scope.toView(type,id);
            }
        };
        //}

        //停留20秒，发送统计
        if ($stateParams.sphone) {
            $interval(function () {
                if($faPlatform.weChat) {
                    $faAPI.shops.gotoUserShopForJpush({
                        shopId: $scope.phone
                    }).then();
                }
            }, 20000, 1)
        }

        $scope.showcomment = false;
        //动态评论
        $scope.saysayComment;
        var saysayId;
        $scope.ckcomment = function(id){

            $scope.showcomment = !$scope.showcomment;
            saysayId = id;
            console.log(saysayId);

        };
        $scope.sendComment = function($event){
            $event.stopPropagation();

            if($scope.saysayComment){
                $faAPI.shops.addFpFaUserSaysayComment({
                    saysayId:saysayId,
                    saysayComment:$scope.saysayComment
                }).then(function(json){
                    $faPopup.alert({
                        title:'评论成功'
                    });
                    $scope.showcomment  = false;
                    //评论展示，评论完毕失去焦点
                    getshopUserSaySay();

                });
            }

        };
        //获取说说评论数据
        function  getlistcomment(){
            $faAPI.shops.listFpFaUserSaysayComment({
                saysayId:saysayId,
                saysayComment:$scope.saysayComment
            }).then(function(json){



            });
        }
        $scope.shophome_head_center = false;
        $scope.ckshowHeadcen = function($event){
            $event.stopPropagation();
            if($scope.shophome_head_center){
                $scope.shophome_head_center = false;
            }else {
                $scope.shophome_head_center = true;
            }
        };
        $scope.isshowinfo = true;
        var shophome_info_div3 = document.getElementById('shophome-info-div3');
        var shophome_info_div2 = document.getElementById('shophome-info-div2');
        $scope.ckIsshowinfo = function(){

            if (!$scope.isshowinfo){
                shophome_info_div3.style.maxHeight = '300px';
                shophome_info_div2.className  = 'shophome-info-div2-hide';

                $scope.isshowinfo = true;

            }else {
                shophome_info_div3.style.maxHeight = '0px';
                shophome_info_div2.className  = 'shophome-info-div2';
                $scope.isshowinfo = false;

            }

        };
        $scope.delete = function(id){
            var myPopup = $ionicPopup.show({
                title: '确定删除该条动态',
                scope: $scope,
                buttons: [
                    {
                        text: '取消',
                        type: 'bolgsDeleteCancel'
                    },
                    {
                        text: '删除',
                        type: 'deletebolgs',
                        onTap: function(e) {
                            $faAPI.blogs.blogDelete({id:id}).then(function(json){

                            })
                        }
                    }
                ]
            });
        };

        function msgviewimg(){

            $scope.ckShowImg = function(imgurl,$index){
                //mySwiper.slideTo($index);

                $scope.showviewimg = true;
                $scope.viewimgurl = imgurl;

                 $scope.mySwiper = new Swiper('.swiper-shoppreview .swiper-container', {
                    direction: 'horizontal',
                    initialSlide: $index,
                    // 如果需要分页器
                    pagination: '.swiper-pagination',
                    observer: true,//修改swiper自己或子元素时，自动初始化swiper
                    observeParents: true//修改swiper的父元素时，自动初始化swiper
                })
            };
            $scope.ckHideImg = function(imgurl){
                if($scope.mySwiper) {//销毁swiper对象
                    $scope.mySwiper.destroy(true, false)
                }

                for(var i=0; i<imgurl.length; i++) {
                    imgurl[i].id = i;
                }
                $scope.viewimgurl = imgurl;
                $scope.showviewimg = false;
            }
        }
        msgviewimg();

        $scope.cropPhotoShopHome = function(){
            //1用户头像/2店铺头像/3店铺背景
            if(!ISWEB){
                if($faPlatform.IOSAPP){
                    cropPhoto('sendImage3');
                }

                if($faPlatform.androidAPP){

                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        cordova.exec(null, null, "MyPlugin", "cropPhoto", ['sendImage3']);
                    }

                }
            }

        };

        window.sendImage3 = function(url){

            $scope.shopperUserInfoDto.shopBackground = url;

            $faAPI.shops.updateShopperUserInfo({
                shopBackground:url,
                updateType:3
            }).then(function(json){
                $faPopup.alert({
                    title:'保存成功'
                });

            });

        };
        //open app
        // document.getElementById('openApp').onclick = function(e){
        //     // 通过iframe的方式试图打开APP，如果能正常打开，会直接切换到APP，并自动阻止a标签的默认行为
        //     // 否则打开a标签的href链接
        //     //微信白名单限制-----del
        //     console.log(e);
        //     document.getElementById('openAppView').style.display = 'none';
        //     //this.style.display = 'none';
        //     //var ifr = document.createElement('iframe');
        //     //ifr.src = 'weixin://dl/profile';
        //     //ifr.style.display = 'none';
        //     //document.body.appendChild(ifr);
        //     //window.setTimeout(function(){
        //     //    alert('error');
        //     //    document.body.removeChild(ifr);
        //     //},3000)
        // };

        $scope.hideFooter = function () {
            document.getElementById('openAppView').style.display = 'none';
        }

        $scope.wid = Math.ceil(window.innerWidth/8)*5
        console.log($scope.wid)
        $scope.myObj = {

            "height": $scope.wid + 'px'
        }


        // $scope.imgheig = .height()
        // console.log($('.aclist_list_i img'))

        $scope.imghe = function(index){
            // console.log(index)
            var _img =  document.getElementById('shopaclist'+index)
            // console.log('shopaclist'+index)
            // console.log(_img)

            // _img.style.top = -Math.ceil(_img.height/2) - $scope.wid/2 + 'px'
            if((_img.height - $scope.wid)>0){
                _img.style.top = -Math.ceil((_img.height - $scope.wid)/2) + 'px'
            }
            if((_img.height - $scope.wid)<0){
                // _img.style.height = $scope.wid +'px';
                _img.style.top = -Math.ceil((_img.height - $scope.wid)/2) + 'px'
            }

            // e.$$nextSibling.$index


            // return Math.ceil(e.$index.height/2) - $scope.wid/2 + 'px'

        }
       /* setTimeout(function(){
            var classImg = document.getElementsByClassName('list_img');

            for(var i=0;i<classImg.length;i++){
                mass =  classImg[i]
                sassWidth = classImg[i].offsetWidth;

                mass.style.height = sassWidth+'px'
            }

        },200)*/

    })

    .controller('shopsProductCtrl', function ($scope, $rootScope,$location, $stateParams, $faAPI, $interval, $faPopup, $ionicPopup, $faUtil, $faUser, $state, $faPlatform, $filter, $ionicHistory,$faModal) {
        $faUser.update();
        $scope.sphone = $stateParams.sphone;
        $scope.isonmsg = $stateParams.isonmsg;
        //console.log($rootScope.shopUserPhone)
        //此参数用来控制两个结果的返回
        //1-来自添加产品成功后-此页面要返回到首页，2、其它普通进入返回对应的上一级
        $scope.isuploadok = $stateParams.isuploadok;
        $scope.useravatar = $faUser.info.avatar;

        //产品初始化查询
        initDate('1');
        function initDate(productState){
            $faAPI.shops.productList({pageNo: 1, pageSize: 100,mobile:$stateParams.sphone, productState:productState}).then(function (json) {
                console.info(json)
                var h2 = json.list.map(function (item) {
                    if (item.fpFundInfoDTO) {
                        item.fpFundInfoDTO.lsjzJson = item.fpFundInfoDTO.lsjzJson ? $faUtil.fromJson((item.fpFundInfoDTO.lsjzJson).replace(/“/g, '"')) : '';
                    } else if (item.productDTO) {
                        if (item.productDTO.expectSaleAmount != 0) {
                            item.productDTO.process = ((item.productDTO.allSubscriptionAmount * 100 / item.productDTO.expectSaleAmount).toFixed(2) > 100) ?
                                100 :
                                (item.productDTO.allSubscriptionAmount * 100 / item.productDTO.expectSaleAmount).toFixed(2);
                        } else {
                            item.productDTO.process = 0;
                        }
                    }
                    return item;
                });



                $scope.hotList2 = h2;
                $scope.shopperUserInfo  = json.shopperUserInfo;
            });
        }

        $scope.productState = '1';//默认查询上架产品
        $scope.queryProduct = function(productState) {
            $scope.productState = productState;
            initDate(productState);
        };
        //下拉刷新
        $scope.doRefresh = function (name) {
            $faAPI.shops.productList({pageNo: 1, pageSize: 100, productState:$scope.productState}).then(function (json) {
                console.info(json)
                var h2 = json.list.map(function (item) {
                    if (item.fpFundInfoDTO) {
                        item.fpFundInfoDTO.lsjzJson = item.fpFundInfoDTO.lsjzJson ? $faUtil.fromJson((item.fpFundInfoDTO.lsjzJson).replace(/“/g, '"')) : '';
                    } else if (item.productDTO) {
                        if (item.productDTO.expectSaleAmount != 0) {
                            item.productDTO.process = ((item.productDTO.allSubscriptionAmount * 100 / item.productDTO.expectSaleAmount).toFixed(2) > 100) ?
                                100 :
                                (item.productDTO.allSubscriptionAmount * 100 / item.productDTO.expectSaleAmount).toFixed(2);
                        } else {
                            item.productDTO.process = 0;
                        }
                    }
                    return item;
                });



                $scope.hotList2 = h2;
                $scope.shopperUserInfo  = json.shopperUserInfo;
                $scope.$broadcast('scroll.refreshComplete');
            });
        };

        $scope.$on("$ionicView.enter", function () {
            //页面启动缓存时,其controller中不会反复执行，但会执行此监听-
            //用此来更新tab数据
            //switchTab();
            //通过变量来判断页面如果是从产品管理进入，刷新所有数据
            console.log($rootScope.isExitProAdd);
            if($rootScope.isExitProAdd){
                initDate('1');
            }

        });
        $scope.toView = function (type, id) {
            if (type && id) {
                var url = '';

                if (type == '01') {
                    url = 'product.simu';
                } else if (type == '02' || type == '03' || type == '07') {
                    url = 'product.shopxtzgdetail';
                } else if (type == '06') {
                    url = 'product.shoppevc';
                }
                if(!$stateParams.sphone){
                    $state.go(url, {id: id});
                }else {
                    $state.go(url, {id: id, share: 'true', sharePhone: $scope.sphone});
                }

            } else {
                console.log('error,,');
            }

        };
        $scope.product2godetail = function(proSource,type,id,myid){
            //id平台产品code,自有产品id
            console.log(id);
            if(proSource == 'self'){
                if(!$stateParams.sphone){
                    $state.go('myProduct2Detail', {id: myid});
                }else {
                    $state.go('myProduct2Detail', {id: myid, share: 'true', sharePhone: $scope.sphone});
                }

            }else {
                $scope.toView(type,id);
            }
        };
        $scope.goProductEdit = function(){};
        //店铺-产品管理-删除--平台
        $scope.productAddToShop = function (pt, product, $event) {
            $event.stopPropagation();//阻止事件冒泡，除非toview点击事件
            if (product && pt) {
                var param = {productType: pt};
                if (pt != '01') {
                    param.productId = product.code;
                } else {
                    param.productId = product.id;
                }
                console.log(param);


                $faPopup.confirm({
                    title: '确定删除该产品？',
                    cancelText: '取消',
                    okText: '确定',
                    okType: 'button-positive confirmLogin'
                }, function (res) {
                    if (res) {
                        $faAPI.shops.productDeleteToShops(param).then(function (json) {
                            console.log(json)
                            if (json) {
                                if (!json.statusCode) {
                                   /* $faPopup.alert({
                                      title: '删除成功'
                                    });*/

                                   // $state.reload();

                                        $scope.queryProduct($scope.productState)

                                    console.log( $scope.productState)



                                }
                            }
                        });
                    }
                });

            }
        };
        //店铺-产品管理-删除--自有产品
        $scope.produc2del = function (id,$event) {
            $event.stopPropagation();//阻止事件冒泡，除非toview点击事件
            if (id) {




                $faPopup.confirm({
                    title: '确定删除该产品？',
                    cancelText: '取消',
                    okText: '确定',
                    okType: 'button-positive confirmLogin'
                }, function (res) {
                    if (res) {
                        $faAPI.shops.deleteFpShopUserRelProduct({
                            id:id
                        }).then(function (json) {
                            console.log(json)
                            if (json) {
                                if (!json.statusCode) {
                                    /* $faPopup.alert({
                                     title: '删除成功'
                                     });*/

                                    // $state.reload();

                                    $scope.queryProduct($scope.productState)

                                    console.log( $scope.productState)



                                }
                            }
                        });
                    }
                });

            }
        };
        //店铺-产品管理-置顶
        $scope.shopProductTop = function (pt, product, $event) {
            $event.stopPropagation();
            if (product && pt) {
                var param = {productType: pt};
                if (pt != '01') {
                    param.productId = product.code;
                } else {
                    param.productId = product.id;
                }
                console.log(param);

                $faAPI.shops.shopProductTop(param).then(function (json) {
                    if (json) {
                        if (!json.statusCode) {
                            $faPopup.alert({
                                title: '置顶成功'
                            });
                            $state.reload();
                        }
                    }
                });
            }

        };
        //店铺-产品管理-推荐
        $scope.shopProductTuijian = function (pt, product, flagTuijian, $event) {
            $event.stopPropagation();
            //flagTuijian--1 推荐，2-取消推荐
            var param = {productType: pt};

            if (pt != '01') {
                param.productId = product.code;
            } else {
                param.productId = product.id;
            }
            console.log(param);
            if (flagTuijian == 1) {
                param.flagTuijian = '2';
                $faAPI.shops.shopProductTuijian(param).then(function (json) {
                    if (json) {
                        if (!json.statusCode) {
                            $faPopup.alert({
                                title: '取消推荐成功'
                            });
                            $state.reload();
                        }
                    }
                });
            } else {

                $scope.data = {};
                param.flagTuijian = '1';
                // 自定义弹窗
                var myPopup = $ionicPopup.show({
                    title: '推荐理由',
                    template: '<textarea  rows="5" cols="15" maxlength="50" placeholder="50字以内" ng-model="data.tuijianReson"></textarea>',
                    inputPlaceholder: '10-50字',
                    scope: $scope,
                    buttons: [
                        {text: '取消推荐'},
                        {
                            text: '<b>确认推荐</b>',
                            type: 'button-positive',
                            onTap: function (e) {

                                if ($scope.data.tuijianReson == '') {
                                    e.preventDefault();
                                    $faPopup.alert({
                                        title: '请填写推荐理由'
                                    });
                                }
                                if (!$scope.data.tuijianReson) {
                                    e.preventDefault();
                                    $faPopup.alert({
                                        title: '请填写推荐理由'
                                    });
                                }
                                return $scope.data.tuijianReson;

                            }
                        }
                    ]
                });
                myPopup.then(function (res) {
                    console.log(res);
                    if (res) {
                        param.tuijianReson = res;
                        console.log(param);
                        $faAPI.shops.shopProductTuijian(param).then(function (json) {
                            if (json) {
                                if (!json.statusCode) {
                                    $faPopup.alert({
                                        title: '推荐成功'
                                    });
                                    $state.reload();
                                }
                            }
                        });
                    }

                });
                //  $ionicPopup.prompt({
                //    title: '推荐理由',
                //    inputType: 'textarea',
                //    inputPlaceholder: '10-50字',
                //    cancelText: '取消推荐',
                //    okText: '确认推荐'
                //  }).then(function (res) {
                //    console.log(res);
                //    if(res == ''){
                //      $faPopup.alert({
                //        title: '请填写推荐理由'
                //      });
                //    }
                //    if (res) {
                //      param.tuijianReson = res;
                //      console.log(param);
                //      $faAPI.shops.shopProductTuijian(param).then(function (json) {
                //        if (json) {
                //          if (!json.statusCode) {
                //            $faPopup.alert({
                //              title: '推荐成功'
                //            });
                //            $state.reload();
                //          }
                //        }
                //      });
                //    }
                //
                //  });
                //
            }


        };

        //上下架产品--平台产品
        $scope.upOrDownPro = function(d, status) {
            // console.log(d,status)
            var code ="";
            if(d.productDTO.type=="01"){
                code=d.fpFundInfoDTO.id;
            }else {
                code= d.productDTO.code;
            }

            $faAPI.shops.upOrDownProduct({proid: code, protype: d.productDTO.type, status: status, mobile:$stateParams.sphone}).then(function(res){
                console.log(res)
                var title = "下架成功!"
                if(status=='1') {
                    title = "上架成功！"

                } else {
                    title = "下架成功!";

                }

                console.log(res)


                $faPopup.alert({
                  title: title
                });

                //$state.reload();
                $scope.queryProduct($scope.productState)
                console.log( d.productDTO)
                console.log( d.productDTO.type)
                console.log( status)
            })
        };
        //上下架产品--自有产品
        $scope.myupOrDownPro = function(d, status) {
            // console.log(d,status)
            //1上架，2下架
            $faAPI.user.upFpShopUserRelProduct({
                    id: d.productDTO.id,
                    publicStatus : status
                }).then(function(res){
                console.log(res)
                var title = "下架成功!"
                if(status=='1') {
                    title = "上架成功！"

                } else {
                    title = "下架成功!";

                }

                console.log(res)


                $faPopup.alert({
                    title: title
                });

                //$state.reload();
                $scope.queryProduct($scope.productState)
                console.log( d.productDTO)
                console.log( d.productDTO.type)
                console.log( status)
            })
        };

        //分享产品详情 producttype 02 03 07
        var cursharepro;
        $scope.shopxtzgproshare = function (proid, p) {
            $scope.shareProType = 'xtzg';
            $scope.shareProid = proid;
            cursharepro = p;

            btnshareSta(proid)
            //
            $faAPI.product.detail({
                code: proid
            }).then(function (json) {
                console.log(json);

                $scope.item = (function (item) {
                    if (item.expectSaleAmount != 0) {
                        item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                    } else {
                        item.process = 0;
                    }
                    for (var i = 0; i < item.profitAndRebateList.length; i++) {
                        if (item.profitAndRebateList[i].pIsAgreement == 1) {
                            //是否协议价
                            $scope.isagreement = true;
                        }
                    }
                    return item;
                })(json.result);

                //分享结束执行
                window.shareCallBack = function () {
                    var param = {
                        productType: $scope.item.productType,
                        productId: $scope.item.productCode
                    };
                    $faAPI.shops.productAddToShopsShare(param).then(function (json) {
                    });
                }
                //微信简版版本
                //未登录的情况下也可以分享产品
                var data;
                if ($faUser.info.isLogin) {
                    //$rootScope.modal.login();
                    //5.信托、资管：投资领域、付息方式、大小配比
                    data = {
                        title: $scope.item.productShortName,
                        desc: '投资领域：' + $scope.item.investDesc + '；付息方式：' + $scope.item.paymentInterestTypeDesc + '；大小配比：' + $scope.item.pSizeRatioExplain,
                        link: reqUrl + '/#/product/xtzgdetail/' + $scope.item.productCode + '?share=true&sharePhone=' + $faUser.info.mobile,
                        imgUrl: citeImgUrl + $scope.item.pImageUrl
                    };

                } else {
                    data = {
                        title: $scope.item.productShortName,
                        desc: '投资领域：' + $scope.item.investDesc + '；付息方式：' + $scope.item.paymentInterestTypeDesc + '；大小配比：' + $scope.item.pSizeRatioExplain,
                        link: reqUrl + '/#/product/xtzgdetail/' + $scope.item.productCode + '?share=true',
                        imgUrl: citeImgUrl + $scope.item.pImageUrl
                    };
                }

                if ($faPlatform.androidAPP) {
                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        cordova.exec(null, null, "MyPlugin", "toShare", [data.title, data.desc, data.link, data.imgUrl]);
                    }

                    window.shareCallBack();
                } else {
                    productShare(data.title, data.desc, data.link, data.imgUrl);
                }
            });

        };

        //分享产品详情--自营产品
        $scope.shopsselfshare = function (proid, p) {

            $scope.shareProType = 'self';
            cursharepro = p;

            btnshareSta(proid)


            $faAPI.product.detailFpShopUserRelProduct({
                id: proid
            }).then(function(json){
                console.log(json);

                $scope.item = json.dto;

                //分享结束执行
                window.shareCallBack = function () {
                    var param = {
                        productType: $scope.item.productType,
                        productId: $scope.item.productCode
                    };
                    $faAPI.shops.productAddToShopsShare(param).then(function (json) {
                    });
                };
                //微信简版版本
                //未登录的情况下也可以分享产品
                var data;
                if ($faUser.info.isLogin) {
                    //$rootScope.modal.login();
                    //5.信托、资管：投资领域、付息方式、大小配比
                    data = {
                        title: $scope.item.productName,
                        desc: '产品期限：' + $scope.item.dueTime + '；付息方式：' +$filter('getInterestType')($scope.item.paymentInterestType),
                        link: reqUrl + '/#/myProduct2Detail'  + '?id='+$scope.item.id+'&share=true&isshare=true&sharePhone=' + $faUser.info.mobile,
                        imgUrl: 'http://static.superfa.cn/upload/jincs/imgsc/logo.png'
                    };

                } else {
                    data = {
                        title: $scope.item.productName,
                        desc: '产品期限：' + $scope.item.dueTime + '；付息方式：' +$filter('getInterestType')($scope.item.paymentInterestType),
                        link: reqUrl + '/#/myProduct2Detail' +'?id='+$scope.item.id+'&isshare=true',
                        imgUrl: 'http://static.superfa.cn/upload/jincs/imgsc/logo.png'
                    };
                }

                if ($faPlatform.androidAPP) {
                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        //cordova.exec(null, null, "MyPlugin", "toShare", [data.title, data.desc, data.link, data.imgUrl]);
                        cordova.exec(null, null, "MyPlugin", "toActivityShare", [data.title, data.desc, data.link, data.imgUrl]);
                    }

                    window.shareCallBack();
                } else {
                    //productShare(data.title, data.desc, data.link, data.imgUrl);
                    actionShare(data.title, data.desc, data.link, data.imgUrl);
                }
            });
        };

        //点击分享按钮统计
        function btnshareSta(proid) {

            var reqData = {
                type: '110503',
                host: $location.host(),
                path: $location.path(),
                param: proid,
                source: 'WAP',
                shopId: $rootScope.shopUserPhone,
                userId: $faUser.info.mobile

            };
            $faAPI.shops.statis({
                type: 'statisitics',
                data: reqData
            }).then(function (json) {
            });
        }

        //私募分享 producttype 01
        $scope.simuproshare = function(proid, p){
            $scope.shareProType = 'simu';
            $scope.shareProid = proid;
            cursharepro = p;

            btnshareSta(proid)
            $faAPI.product.simuDetail({
                id: proid
            }).then(function(res){
                $scope.item = res;

                //分享结束执行
                window.shareCallBack = function() {
                    var param = {
                        productType: '01',
                        productId: $scope.item.detail.id
                    };
                    $faAPI.shops.productAddToShopsShare(param).then(function(json) {});
                };
                var data;
                if ($faUser.info.isLogin) {
                    //阳光私募：基金类型、组织形式、结构形式
                    data = {
                        title:$scope.item.detail.jjqc,
                        desc:'基金类型：'+$scope.item.detail.jjfl+'；组织形式：'+$scope.item.detail.zzxs+'；结构形式：'+$scope.item.detail.jgxs,
                        link:reqUrl + '/#/product/simu/' + $scope.item.detail.id+'?share=true&sharePhone='+$faUser.info.mobile+'&onlypro=true',
                        imgUrl:'http://lec.superfa.cn/upload/bann/20160913/1473730864215990394.png'
                    };
                }else {
                    //阳光私募：基金类型、组织形式、结构形式
                    data = {
                        title:$scope.item.detail.jjqc,
                        desc:'基金类型：'+$scope.item.detail.jjfl+'；组织形式：'+$scope.item.detail.zzxs+'；结构形式：'+$scope.item.detail.jgxs,
                        link:reqUrl + '/#/product/simu/' + $scope.item.detail.id+'?share=true',
                        imgUrl:'http://lec.superfa.cn/upload/bann/20160913/1473730864215990394.png'
                    };
                }

                if($faPlatform.androidAPP){
                    document.addEventListener("deviceready",OnDeviceReady, false);
                    function OnDeviceReady()
                    {
                        cordova.exec(null, null, "MyPlugin", "toShare", [data.title,data.desc,data.link,data.imgUrl]);
                    }
                    window.shareCallBack();
                }else{
                    productShare(data.title,data.desc,data.link,data.imgUrl);
                }
            })

        };

        //分享产品详情 06
        $scope.shoppevcproshare = function(proid, p){
            $scope.shareProType = 'pevc';
            $scope.shareProid = proid;
            cursharepro = p;

            btnshareSta(proid)
            $faAPI.product.pevcDetail({
                code: proid
            }).then(function(json){

                $scope.item = (function(item) {
                    if (item.expectSaleAmount != 0) {
                        item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                    } else {
                        item.process = 0;
                    }
                    for(var i=0;i<item.profitAndRebateList.length;i++){
                        if(item.profitAndRebateList[i].pIsAgreement == 1){
                            //是否协议价
                            $scope.isagreement = true;
                        }
                    }
                    return item;
                })(json.result);

                //分享结束执行
                window.shareCallBack = function() {
                    var param = {
                        productType: $scope.item.productType,
                        productId: $scope.item.productCode
                    };
                    $faAPI.shops.productAddToShopsShare(param).then(function(json) {});
                };
                var data;
                $scope.item.peOrganizeShape= $filter('zuzhixingshi')($scope.item.peOrganizeShape);
                if ($faUser.info.isLogin) {
                    //7.股权基金： 发行机构、组织形式、基金类型
                    data = {
                        title:$scope.item.productShortName,
                        desc:'发行机构：'+$scope.item.investOwner+'；组织形式：'+$scope.item.peOrganizeShape+'；基金类型：'+$scope.item.peFundShape,
                        link:reqUrl + '/#/product/pevc/' + $scope.item.productCode+'?share=true&sharePhone='+$faUser.info.mobile,
                        imgUrl:citeImgUrl+$scope.item.pImageUrl
                    };

                }else {
                    //7.股权基金： 发行机构、组织形式、基金类型
                    data = {
                        title:$scope.item.productShortName,
                        desc:'发行机构：'+$scope.item.investOwner+'；组织形式：'+$scope.item.peOrganizeShape+'；基金类型：'+$scope.item.peFundShape,
                        link:reqUrl + '/#/product/pevc/' + $scope.item.productCode+'?share=true',
                        imgUrl:citeImgUrl+$scope.item.pImageUrl
                    };
                }

                if($faPlatform.androidAPP){
                    document.addEventListener("deviceready",OnDeviceReady, false);
                    function OnDeviceReady()
                    {
                        cordova.exec(null, null, "MyPlugin", "toShare", [data.title,data.desc,data.link,data.imgUrl]);
                    }
                    window.shareCallBack();
                }else{
                    productShare(data.title,data.desc,data.link,data.imgUrl);
                }
            });

        };

        //发送邮件、复制简版
        {
            $scope.mailData = {};

            $faModal('send_mail','views/modals/sendMail.html',$scope,{
                initialize:function(){
                    //console.log($scope.modal.send_mail());
                    //console.log(cursharepro)
                },
                done:function(){
                    var self = this;

                    var pid, pType;
                    if(cursharepro) {
                        if ($scope.shareProType == 'pevc') {
                            pid = cursharepro.productDTO.id;
                            pType = cursharepro.pType;
                        } else if ($scope.shareProType == 'simu') {
                            pid = cursharepro.fpFundInfoDTO.id;
                            pType = cursharepro.pType
                        } else if ($scope.shareProType == 'xtzg') {
                            pid = cursharepro.productDTO.id;
                            pType = cursharepro.pType;
                        }

                        if (pid && pType) {
                            $faAPI.product.sendMail({
                                pId: pid,
                                pType: pType,
                                emailAddress: $scope.mailData.sendMailUrl
                            }).then(function () {
                                $ionicPopup.alert({
                                    title: '发送邮件成功'
                                });
                                $rootScope.snedMailHistory.push($scope.mailData.sendMailUrl);
                                $rootScope.snedMailHistory = unique2($rootScope.snedMailHistory.reverse());
                                self.hide();
                            });
                        }
                    }
                }
            });
            //发送邮件
            window.showSendMail = function(){
                $scope.modal.send_mail();
            };

            //清空发送邮件历史记录
            $scope.delsnedEmailHis = function(){
                $rootScope.snedMailHistory = [];
            };

            //复制简版功能提示
            //if($faPlatform.androidAPP || $faPlatform.IOSAPP){
            //    var hintv = document.getElementById('hintcopy');
            //    if(!window.localStorage.ishintCopy){
            //        hintv.style.display = 'block';
            //    }
            //    $scope.hidehintCopy = function(){
            //        hintv.style.display = 'none';
            //        window.localStorage.ishintCopy = true;
            //    };
            //}
            //复制简版
            $faModal('copy_brief','views/modals/copyBrief.html',$scope,{
                initialize:function(){
                    console.info(this.data)
                    $scope.copyType = $scope.shareProType;//产品类型 pevc、
                    //项目亮点
                    if($scope.copyType == 'pevc') {
                        try {
                            if($scope.shareProid) {
                                $faAPI.product.pevcDetail({
                                    code: $scope.shareProid
                                }).then(function (json) {
                                    var summary = JSON.parse(json.result.summary);

                                    if (json.result.flagBaoxiao) {
                                        $scope.copyisbaoxiao = '***SFA独家包销***';
                                    }
                                    $scope.copyxmld = summary.xmld ? summary.xmld.replace(/<[^>]+>/g, "") : '-';
                                    if ($faUser.info.isLogin) {

                                        $scope.copyuserinfo = '';
                                        if ($faUser.info.realName) {
                                            $scope.copyuserinfo = '联系人:' + $faUser.info.realName;
                                        }
                                        $scope.copyuserinfo = $scope.copyuserinfo + ' 联系电话:' + $faUser.info.mobile;
                                    }
                                })
                            }
                        } catch (err) {

                        }
                    } else if($scope.copyType == 'simu') {
                        try {
                            if($scope.shareProid) {
                                $faAPI.product.simuDetail({id: $scope.shareProid}).then(function (json) {

                                    //认购须知
                                    $scope.copybuynoticedetail = json.buynotice.buynoticedetail ? json.buynotice.buynoticedetail.replace(/<[^>]+>/g, "") : '-';
                                    //项目亮点
                                    $scope.copyproductadvantage = json.buynotice.productadvantage ? json.buynotice.productadvantage.replace(/<[^>]+>/g, "") : '-';
                                    if ($faUser.info.isLogin) {

                                        $scope.copyuserinfo = '';
                                        if ($faUser.info.realName) {
                                            $scope.copyuserinfo = '联系人:' + $faUser.info.realName;
                                        }
                                        $scope.copyuserinfo = $scope.copyuserinfo + ' 联系电话:' + $faUser.info.mobile;
                                    }
                                });
                            }

                        }catch(err){

                        }
                    } else if($scope.copyType == 'xtzg') {
                        if($scope.shareProid) {
                            $faAPI.product.detail({code: $scope.shareProid}).then(function(res){
                                var summary = JSON.parse(res.result.summary);

                                //是否包销
                                if (res.result.flagBaoxiao) {
                                    $scope.copyisbaoxiao = '***SFA独家包销***';
                                }
                                //资金用途
                                $scope.copyzjyt = summary.zjyt ? summary.zjyt.replace(/<[^>]+>/g, "") : '-';
                                //风险控制
                                $scope.copyfxkz = summary.fxkz ? summary.fxkz.replace(/<[^>]+>/g, "") : '-';
                                //产品优势
                                $scope.copycpys = summary.cpys ? summary.cpys.replace(/<[^>]+>/g, "") : '-';
                                //募集账号
                                $scope.copymjzh = summary.mjzh ? summary.mjzh.replace(/<[^>]+>/g, "") : '-';
                                if ($faUser.info.isLogin) {

                                    $scope.copyuserinfo = '';
                                    if ($faUser.info.realName) {
                                        $scope.copyuserinfo = '联系人:' + $faUser.info.realName;
                                    }
                                    $scope.copyuserinfo = $scope.copyuserinfo + ' 联系电话:' + $faUser.info.mobile;
                                }
                            })
                        }
                    } else if($scope.copyType == 'self') {//自营产品

                    }

                },
                done:function(){
                    var data = document.getElementById('copyData').value;

                    if($faPlatform.androidAPP){
                        document.addEventListener("deviceready",OnDeviceReady, false);
                        function OnDeviceReady()
                        {
                            cordova.exec(null, null, "MyPlugin", "copy", [data]);
                        }
                    }else{
                        copy(data);
                    }

                }
            });
            window.showCopyBrief = function(){
                $scope.modal.copy_brief();
            };

        }

        //进入产品管理页埋点统计
        {
            var reqData = {
                type: '110500',
                host: $location.host(),
                path: $location.path(),
                param: $location.search(),
                source: 'WAP',
                shopId: $rootScope.shopUserPhone
            };
            setTimeout(function(){
                $faAPI.shops.statis({
                    type: 'statisitics',
                    data: reqData
                }).then(function (json) {
                });
            }, 800)
        }

        //产品图文二维码
        {
            // $faModal('proqrcode','views/modals/proqrcode.html',$scope,{
            //    initialize:function(){
            //        console.info($scope.item)
            //        $scope.proitem = angular.copy($scope.item);
            //        console.info($scope.proitem)
            //        if($scope.shareProType=='simu') {//私募
            //            $scope.proitem.detail.lsyjbJson = $scope.proitem.detail.lsyjbJson ? $faUtil.fromJson(($scope.proitem.detail.lsyjbJson).replace(/“/g, '"')) : false;
            //            $scope.proitem.detail.lsjzJson = $scope.proitem.detail.lsjzJson ? $faUtil.fromJson(($scope.proitem.detail.lsjzJson).replace(/“/g, '"')) : false;
            //
            //            $scope.proerweimaurl = $rootScope.baseUrl +"/"+APITYPE+ "/api/QRcode/prodqrcode?proid="+$scope.proitem.detail.id+"&protype=simu"
            //        } else if($scope.shareProType=='pevc') {//股权基金
            //
            //            $scope.proerweimaurl = $rootScope.baseUrl +"/"+APITYPE + "/api/QRcode/prodqrcode?proid="+$scope.proitem.productCode+"&protype=pevc"
            //
            //        } else if($scope.shareProType=='self') {//自营产品
            //
            //            $scope.proitem.revenue = $scope.proitem.revenue?$faUtil.fromJson($scope.proitem.revenue) : false;
            //            $scope.proerweimaurl = $rootScope.baseUrl +"/"+APITYPE + "/api/QRcode/prodqrcode?proid="+$scope.proitem.id+"&protype=self"
            //
            //        } else if($scope.shareProType=='xtzg') {//其他
            //
            //            $scope.summary = JSON.parse($scope.proitem.summary);
            //            $scope.proerweimaurl = $rootScope.baseUrl +"/"+APITYPE + "/api/QRcode/prodqrcode?proid="+$scope.proitem.productCode+"&protype=xtzg"
            //        }
            //
            //        //用户信息
            //        $faAPI.shops.shopUserInfo({
            //            loginName: $faUser.info.mobile
            //        }).then(function (json) {
            //            console.info(json);
            //            $scope.shareUserInfo = json.shopperUserInfoDto;
            //        })
            //    },
            //    done:function(){
            //
            //    }
            // });

            $scope.showProdShareQrcode = function(proid, protype){
                // $scope.modal.proqrcode();
                $state.go('prodQRcode', {proid:proid, protype:protype, phone:$rootScope.shopUserPhone})

                // if(ISWEB) {
                //     $state.go('prodQRcode', {proid:proid, protype:protype, phone:$rootScope.shopUserPhone})
                // } else {
                //     // var url = $rootScope.baseUrl+"/#/prodQRcode?proid="+proid+"&protype="+protype+"&phone="+$rootScope.shopUserPhone;
                //     //
                //     // if ($faPlatform.androidAPP) {
                //     //     setTimeout(function(){
                //     //         document.addEventListener("deviceready", OnDeviceReady, false);
                //     //         function OnDeviceReady() {
                //     //             cordova.exec(null, null, "MyPlugin", "screeShot", [url]);
                //     //         }
                //     //     },500)
                //     // } else {
                //     //     screeShot(url)
                //     // }
                // }

                //埋点统计
                setTimeout(function(){//图文二维码按钮埋点
                    var reqData = {
                        type: '110506',
                        host: $location.host(),
                        path: $location.path(),
                        param: $location.search(),
                        source: 'WAP',
                        shopId: $rootScope.shopUserPhone,
                        userId: $faUser.info.mobile
                    };
                    $faAPI.shops.statis({
                        type: 'statisitics',
                        data: reqData
                    }).then(function (json) {
                    });
                });
            };
        }
        //GO 产品中心
        $scope.goProAdd = function(){
            $rootScope.isExitProAdd = false;
            $rootScope.count_statis_btnAndPage('110502', 'app.shopsProductAdd', $rootScope.shopUserPhone, null, null)
        };
        //添加资讯产品关联
        $scope.addFpShopProjectInformation = function(pt, product){
            console.log('addFpShopProjectInformation');
            //参数：
            //private Integer informationId;//资讯ID
            //private String projectId;//产品ID或CODE
            //private String proSource;//产品来源()
            //private String pType;//产品类型
            //private String pName;//产品名称
            //private String pMinimumAmount;//产品起购金额
            //private String expectAnnualRevenue;//预期收益
            //private String dueTime;//产品期限
            //private String saleStatus;//募集状态
            if (product && pt) {
                var param = {pType: pt};
                if (pt != '01') {
                    param.projectId = product.productDTO.code;
                    param.pName = product.productDTO.name;
                    param.pMinimumAmount = product.productDTO.minimumAmount;
                    param.expectAnnualRevenue = product.productDTO.profitHight.expectAnnualRevenue;
                    param.dueTime = product.productDTO.dueTime;
                    param.saleStatus = product.productDTO.saleStatus;
                } else {
                    param.projectId = product.fpFundInfoDTO.id;
                    param.pMinimumAmount = product.fpFundInfoDTO.lsjzJson[0].jzdw;//最新净值
                    param.expectAnnualRevenue = product.fpFundInfoDTO.lsjzJson[0].zdf;//涨跌幅
                    param.dueTime = product.fpFundInfoDTO.jjjlmc;//基金经理
                    param.pName = product.fpFundInfoDTO.jjmc;//基金名称

                }
                console.log(param);
                if($scope.isonmsg != 'nomad'){
                    param.informationId = $scope.isonmsg;
                }
                param.proSource = product.proSource;



                $faAPI.shops.addFpShopProjectInformation(param).then(function(json){
                    console.log(json);
                    if (json) {
                        if (!json.statusCode) {
                            $faPopup.alert({
                                title: '添加成功'
                            });
                            $ionicHistory.goBack();
                            //window.history.back();
                        }
                    }
                });
            }

        }


    })

    .controller('prodQRcodeCtrl',function($scope,$rootScope,$faAPI,$faUser,$faUtil,$stateParams,$faPopup,$interval,$location,$faPlatform){
        var proid = $stateParams.proid, protype = $stateParams.protype,  phone = $stateParams.phone;
        $scope.shareProType = protype;
        if(protype=='xtzg') {//信托、资管、债券
            $faAPI.product.detail({
                code: proid
            }).then(function (json) {
                console.log(json);
                $scope.tuijianReson = json.result.fpsDto.tuijianReson;


                $scope.item = (function (item) {
                    if (item.expectSaleAmount != 0) {
                        item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                    } else {
                        item.process = 0;
                    }
                    for (var i = 0; i < item.profitAndRebateList.length; i++) {
                        if (item.profitAndRebateList[i].pIsAgreement == 1) {
                            //是否协议价
                            $scope.isagreement = true;
                        }
                    }
                    return item;
                })(json.result);

                //产品详情由富文本拆分的字段
                try {
                    $scope.summary = JSON.parse($scope.item.summary);
                }
                catch (err) {
                }

                //二维码
                $scope.proerweimaurl = $rootScope.baseUrl +"/"+APITYPE + "/api/QRcode/prodqrcode?proid="+$scope.item.productCode+"&protype=xtzg&userPhone="+phone
            });
        } else if(protype=='self') {//自营产品
            $faAPI.product.detailFpShopUserRelProduct({
                id: proid
            }).then(function(json) {
                console.log(json);

                $scope.item = json.dto;

                $scope.item.revenue = $scope.item.revenue?$faUtil.fromJson($scope.item.revenue) : false;
                //二维码
                $scope.proerweimaurl = $rootScope.baseUrl +"/"+APITYPE + "/api/QRcode/prodqrcode?proid="+$scope.item.id+"&protype=self&userPhone="+phone
            })
        } else if(protype=='simu') {//私募
            $faAPI.product.simuDetail({
                id: proid
            }).then(function(res) {
                console.log(res)
                $scope.item = res;
                $scope.tuijian = $scope.item.detail.fpsDto.tuijianReson;
                $scope.item.detail.lsyjbJson = $scope.item.detail.lsyjbJson ? $faUtil.fromJson(($scope.item.detail.lsyjbJson).replace(/“/g, '"')) : false;
                $scope.item.detail.lsjzJson = $scope.item.detail.lsjzJson ? $faUtil.fromJson(($scope.item.detail.lsjzJson).replace(/“/g, '"')) : false;

                //二维码
                $scope.proerweimaurl = $rootScope.baseUrl +"/"+APITYPE+ "/api/QRcode/prodqrcode?proid="+$scope.item.detail.id+"&protype=simu&userPhone="+phone
            })
        } else if(protype=='pevc') {//股权基金
            $faAPI.product.pevcDetail({
                code: proid
            }).then(function(json) {
                console.log(json)
                $scope.item = (function (item) {
                    if (item.expectSaleAmount != 0) {
                        item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                    } else {
                        item.process = 0;
                    }
                    for (var i = 0; i < item.profitAndRebateList.length; i++) {
                        if (item.profitAndRebateList[i].pIsAgreement == 1) {
                            //是否协议价
                            $scope.isagreement = true;
                        }
                    }
                    return item;
                })(json.result);


                //二维码
                $scope.proerweimaurl = $rootScope.baseUrl +"/"+APITYPE + "/api/QRcode/prodqrcode?proid="+$scope.item.productCode+"&protype=pevc&userPhone="+phone
            })
        }

        //用户信息
        $faAPI.shops.shopUserInfo({
            loginName: phone
        }).then(function (json) {
            console.info(json);
            $scope.shareUserInfo = json.shopperUserInfoDto;
            $scope.shareUserDto = json.dto;
        })

        $scope.done = function () {//截图分享
            $scope.showproqrcodebtn = false;
            if ($faPlatform.androidAPP) {
                setTimeout(function(){
                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        cordova.exec(null, null, "MyPlugin", "screeShot", []);
                    }
                },500)
            } else {
                screeShot()
            }
        }

        $scope.showproqrcodebtn = true;
        window.showprdqrbtn = function () {
            $scope.showproqrcodebtn = true;
            $scope.$apply();
        }

    })

    .controller('shopsProductAddCtrl', function ($interval, $scope, $rootScope, $ionicHistory, $ionicGesture, $faMAP, $faAPI, $faUtil, $state, $faModal, $faPopup, $timeout, $ionicScrollDelegate, $stateParams, $faUser, $ionicPopup) {
        //     var galleryTop,galleryThumbs
        //
        //
        //      galleryTop = new Swiper('.gallery-top', {
        //         spaceBetween: 10,
        //
        //     });
        //      galleryThumbs = new Swiper('.gallery-thumbs', {
        //
        //         spaceBetween: 10,
        //         centeredSlides: true,
        //         slidesPerView: 'auto',
        //         touchRatio: 0.2,
        //         slideToClickedSlide: true,
        //
        //      });
        // galleryTop.controller.control = galleryThumbs;
        // galleryThumbs.controller.control = galleryTop;
        $scope.index = 0;//初始化
        function initswiper(){
            var tabsSwiper = new Swiper('.gallery-top',{

                onSlideChangeStart: function(swiper){
                    $(".gallery-thumbs .swiper-slide").removeClass('swiper-slide-active')
                    $(".gallery-thumbs .swiper-slide").eq(tabsSwiper.activeIndex).addClass('swiper-slide-active')
                    $scope.index = swiper.activeIndex
                    $scope.issle = 1;
                    $scope.$digest();
                    $scope.sletype = this.index;
                }
            })
            $(".gallery-thumbs .swiper-slide").on('touchstart mousedown',function(e){
                e.preventDefault()
                $(".tabs .active").removeClass('swiper-slide-active')
                $(this).addClass('swiper-slide-active')
                tabsSwiper.slideTo( $(this).index() )
            })
            $(".tabs a").click(function(e){
                e.preventDefault()
            })
        }

        initswiper();


            //产品tab页的推荐
        $scope.hotList = {};
        $scope.issle = 1;
        var sledivs, sletabview;
        $scope.sletype = 0;
        $scope.flagShopQuery = true;
        $scope.addrandom = Math.random();

        sledivs = document.querySelectorAll('#slelist_add>div');
        sletabview = document.getElementById('sletabview');
        sledivs = angular.element(sledivs);
        sletabview = angular.element(sletabview);

        for (var i = 0; i < sledivs.length; i++) {
            sledivs[i].index = i;
            sledivs[i].onclick = function (e) {
                //show(this.index);
                $scope.index = this.index;
                //初始化排序条件
                $scope.issle = 1;
                $scope.$digest();
                $scope.sletype = this.index;
            }
        }

        // function clearClass() {
        //     //console.log('clearclass');
        //     for (var i = 0; i < sledivs.length; i++) {
        //         sledivs[i].className = '';
        //     }
        // }


        function sleNav(index) {
            // clearClass();
            //console.log(index);
            //console.log(sledivs[index]);
            // sledivs[index].className = 'w4-prolist-sle';
        }

        $scope.scrollGoto = function (index) {
            $timeout(function () {
                $ionicScrollDelegate.$getByHandle('mainScroll').scrollTo(index * 100, 0);
            }, 50);
        };
        function switchTab() {
            //根据参数跳转选择菜单
            if ($stateParams.sletype) {
                console.log($stateParams.sletype)
                var sletype = $stateParams.sletype;
                $scope.index = sletype;
                // sleNav(sletype);
                $scope.scrollGoto(sletype);
                return
            }
            switch ($scope.sletype) {
                case 0:
                    $scope.index = 0;
                    // sleNav($scope.index);
                    $scope.scrollGoto($scope.index);

                    break;
                case 1:
                    $scope.index = 1;
                    // sleNav($scope.index);
                    $scope.scrollGoto($scope.index);

                    break;
                case 2:
                    $scope.index = 2;
                    // sleNav($scope.index);
                    $scope.scrollGoto($scope.index);

                    break;
                case 3:
                    $scope.index = 3;
                    // sleNav($scope.index);
                    $scope.scrollGoto($scope.index);
                    break;
                case 4:
                    $scope.index = 4;
                    // sleNav($scope.index);
                    $scope.scrollGoto($scope.index);
                    break;
                default:
                    $scope.index = 0;
                    // sleNav($scope.index);
                    $scope.scrollGoto($scope.index);
                    break;
            }
        }

        //switchTab();


        console.log($scope.index);
        $scope.product = {
            investType: $faMAP.investType,
            annualRevenue: $faMAP.annualRevenue,
            rabateRatio: $faMAP.rabateRatio,
            zero: {
                type: '01',
                data: {},
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: []
            },
            one: {
                type: '02',
                data: {
                    //设置默认值是为了解决，ng-value=07的时候，请求接口的时候变成了7,
                    saleStatus:'',
                    dueTime:'07',
                    annualRevenue:'',
                    pPaymentInterestType:'',
                    pInvestType:'',
                    minimumAmount:'',
                    pSizeRatioType:'',
                    pBelongArea:''
                },
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: [],
                fyFlag: ''
            },
            two: {
                type: '03',
                data: {
                    saleStatus:'',
                    dueTime:'07',
                    annualRevenue:'',
                    pPaymentInterestType:'',
                    pInvestType:'',
                    minimumAmount:'',
                    pSizeRatioType:'',
                    pBelongArea:''
                },
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: [],
                fyFlag: ''
            },
            three: {
                type: '07',
                data: {
                    saleStatus:'',
                    dueTime:'07',
                    annualRevenue:'',
                    pPaymentInterestType:'',
                    pInvestType:'',
                    minimumAmount:'',
                    pSizeRatioType:'',
                    pBelongArea:''
                },
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: [],
                fyFlag: ''
            },
            four: {
                data: {},
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: []
            },
            five: {
                type: '06',
                data: {
                    saleStatus:'',
                    minimumAmount:'05',
                    dueTime:'05',
                    rabateRatio:'04'
                },
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: []
            }
        };
        //首页最新推荐
        $faAPI.customer.recommentProduct({
            recommentType: '2'
        }).then(function (json) {
            $scope.searchName = json.list[0].productDTO.name;
        });

        $scope.$on("$ionicView.enter", function () {
            //页面启动缓存时,其controller中不会反复执行，但会执行此监听-
            //用此来更新tab数据
            //switchTab();
            //通过变量来判断页面如果是从产品管理进入，刷新所有数据
            console.log($rootScope.isExitProAdd);
            if(!$rootScope.isExitProAdd){
                //$scope.sletype = 0;
                //switchTab();
                initswiper();
                $ionicScrollDelegate.scrollTop();
                $scope.doRefresh('one');
                $scope.doRefresh('two');
                $scope.doRefresh('three');
                $scope.doRefresh('four');
                $scope.doRefresh('five');
            }

        });

        //加载更多
        $scope.loadMore = function (name) {
            console.info("刷新："+name);

            if (name == 'one' || name == 'two') {
                $faUtil.extend($scope.product[name].data, {
                    pageSize: $scope.product[name].pager.pageSize,
                    type: $scope.product[name].type,
                    pageNo: $scope.product[name].pager.nextPage,
                    flagShopQuery: $scope.flagShopQuery
                });
                $faAPI.product.list($scope.product[name].data, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {

                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });

                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.product[name].fyFlag = json.fyFlag;

                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            }

            if (name == 'three') {
                $faUtil.extend($scope.product[name].data, {
                    pageSize: $scope.product[name].pager.pageSize,
                    type: $scope.product[name].type,
                    pageNo: $scope.product[name].pager.nextPage,
                    flagShopQuery: $scope.flagShopQuery
                });
                $faAPI.product.list($scope.product[name].data, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {

                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });

                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.product[name].fyFlag = json.fyFlag;

                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            }
            //阳光私募
            if (name == 'four') {
                $faUtil.extend($scope.product[name].data, {
                    pageSize: $scope.product[name].pager.pageSize,
                    pageNo: $scope.product[name].pager.nextPage,
                    flagShopQuery: $scope.flagShopQuery
                });
                $faAPI.product.simuList($scope.product[name].data, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {
                        item.lsjzJson = item.lsjzJson ? $faUtil.fromJson((item.lsjzJson).replace(/“/g, '"')) : '';
                        return item;
                    });

                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            }
            //股权基金
            if (name == 'five') {
                $faUtil.extend($scope.product[name].data, {
                    pageSize: $scope.product[name].pager.pageSize,
                    type: $scope.product[name].type,
                    pageNo: $scope.product[name].pager.nextPage,
                    flagShopQuery: $scope.flagShopQuery
                });
                $faAPI.product.pevcList($scope.product[name].data, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {

                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });

                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.product[name].fyFlag = json.fyFlag;

                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            }
        };

        //下拉刷新
        $scope.doRefresh = function (name) {

            if (name == 'one' || name == 'two') {
                //console.log($scope.product[name]);
                $scope.product[name].data = {
                    saleStatus:'',
                    dueTime:'07',
                    annualRevenue:'',
                    pPaymentInterestType:'',
                    pInvestType:'',
                    minimumAmount:'',
                    pSizeRatioType:'',
                    pBelongArea:''
                };
                $scope.issle = 1;
                $faAPI.product.list({
                    pageSize: 5,
                    type: $scope.product[name].type,
                    pageNo: 1,
                    flagShopQuery: $scope.flagShopQuery

                }, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {

                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });
                    //删除之前的冗余数据
                    $scope.product[name].list = [];
                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;

                    //console.log($scope.product[name]);
                    $scope.$broadcast('scroll.refreshComplete');


                });
            }
            //股权基金
            if (name == 'three') {
                $scope.product[name].data = {
                    saleStatus:'',
                    dueTime:'07',
                    annualRevenue:'',
                    pPaymentInterestType:'',
                    pInvestType:'',
                    minimumAmount:'',
                    pSizeRatioType:'',
                    pBelongArea:''
                };

                $scope.issle = 1;
                $faAPI.product.list({
                    pageSize: 5,
                    type: $scope.product[name].type,
                    pageNo: 1,
                    flagShopQuery: $scope.flagShopQuery
                }, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {

                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });
                    //删除之前的冗余数据
                    $scope.product[name].list = [];
                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    //console.log($scope.product[name]);
                    $scope.$broadcast('scroll.refreshComplete');


                });
            }
            //阳光私募
            if (name == 'four') {

                $faAPI.product.simuList({
                    pageSize: 5,
                    pageNo: 1,
                    flagShopQuery: $scope.flagShopQuery
                }, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {
                        item.lsjzJson = item.lsjzJson ? $faUtil.fromJson((item.lsjzJson).replace(/“/g, '"')) : '';
                        return item;
                    });
                    //删除之前的冗余数据
                    $scope.product[name].list = [];
                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.$broadcast('scroll.refreshComplete');

                });
            }
            if(name == 'five'){
                $scope.product[name].data = {
                    saleStatus:'',
                    minimumAmount:'05',
                    dueTime:'05',
                    rabateRatio:'04'
                };
                $scope.issle = 1;
                $faAPI.product.pevcList({
                    pageSize: 5,
                    type: $scope.product[name].type,
                    pageNo: 1,
                    flagShopQuery:$scope.flagShopQuery
                }, {
                    flag: false
                }).then(function(json) {

                    var list = json.list.map(function(item) {

                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });
                    //删除之前的冗余数据
                    $scope.product[name].list = [];
                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    //console.log($scope.product[name]);
                    $scope.$broadcast('scroll.refreshComplete');


                });
            }
        };

        //排序
        $scope.proSort = function (name, type) {
            //pRabateProfitParameter    佣金 true
            //pAnnualRevenueExpectParameter 收益  true
            $scope.issle = type;
            switch (type) {
                case 1:
                    $scope.product[name].data.pRabateProfitParameter = undefined;
                    $scope.product[name].data.pAnnualRevenueExpectParameter = undefined;
                    break;
                case 2:
                    $scope.product[name].data.pRabateProfitParameter = true;
                    $scope.product[name].data.pAnnualRevenueExpectParameter = undefined;
                    break;
                case 3:
                    $scope.product[name].data.pRabateProfitParameter = undefined;
                    $scope.product[name].data.pAnnualRevenueExpectParameter = true;
                    break;
            }

            $scope.product[name].list = [];

            $scope.product[name].pager = {
                hasNaxtPage: true,
                pageSize: 5,
                nextPage: 1
            };

            $scope.$broadcast('scroll.infiniteScrollComplete');

            //$timeout(function() {
            $ionicScrollDelegate.$getByHandle(name).scrollTop();
            //}, 50);
        };


        //返回顶部
        $scope.goTop = function (index) {
            $ionicScrollDelegate.scrollTop();
            $scope.scrollGoto(index);

        };
        //判断是否到达顶部隐藏
        $scope.getScrollPosition = function (name) {
            var scrollTop = $ionicScrollDelegate.$getByHandle(name).getScrollPosition().top;

            if (scrollTop < 200) {
                $scope.isTop = false;
            } else {
                $scope.isTop = true;
            }
            $scope.$digest();
        };
        $scope.goCertification = function ($event) {
            $event.stopPropagation();
            $faUser.info.isLogin ? $state.go('app.myself.certification') : $rootScope.modal.login();

        };

        //用于其他地方登录后更新产品列表的登录认证状态--2016/11/28
        //window.isprolistUpdate = function(){
        //    window.location.reload();
        //};

        $scope.toView = function (type, id) {

            if (type && id) {
                var url = '';

                if (type == '01') {
                    url = 'product.simu';
                } else if (type == '02' || type == '03' || type == '07') {
                    url = 'product.xtzgdetail';
                } else if (type == '06') {
                    url = 'product.pevc';
                }

                $state.go(url, {id: id});
            } else {
                console.log('error,,');
            }

        };
        $scope.selData = {
            //用于保存选择变量，为何用于对象来保存？
            //涉及modal view 会创建子级作用域和本身的父级作用域，导致这边js中修改变量，不会同步到页面中去
            //这是一种解决方案，原理需要研究
            wap4SleLeft:0
        };
        $scope.ngWap4SleLeft = function(index){
            $scope.selData.wap4SleLeft=index;

            $ionicScrollDelegate.$getByHandle('filterRightScroll').scrollTop();


        };
        //通过比较对象的值改变，判断是否筛选--true 为已筛选
        function isSleFilter(name){
            var d = $scope.product[name].data;
            if(d.saleStatus!='' || d.dueTime != '07' || d.annualRevenue !='' || d.pPaymentInterestType!= ''
                || d.pInvestType != '' || d.minimumAmount !='' || d.pSizeRatioType!='' || d.pBelongArea !=''
            ){
                return true
            }else {
                return false
            }

        }
        $faModal('xtfilter', 'views/product/wap4_xtFilter.html', $scope, {
            initialize: function () {

                var self = this;

            },
            clearFilter:function(){

                $scope.product.one.data = {
                    saleStatus:'',
                        dueTime:'07',
                        annualRevenue:'',
                        pPaymentInterestType:'',
                        pInvestType:'',
                        minimumAmount:'',
                        pSizeRatioType:'',
                        pBelongArea:''
                };
                $scope.isFilterSleOne = false;
            },
            done: function () {

                var self = this;

                $scope.product[self.data.key].list = [];

                $scope.product[self.data.key].pager = {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                };

                $scope.$broadcast('scroll.infiniteScrollComplete');

                $timeout(function () {
                    $ionicScrollDelegate.$getByHandle(self.data.key).scrollTop();
                }, 50);

                self.hide();
                if(isSleFilter('one')){
                    $scope.isFilterSleOne = true;
                }else {
                    $scope.isFilterSleOne = false;
                }


            }
        });
        $faModal('zgfilter', 'views/product/wap4_zgFilter.html', $scope, {
            initialize: function () {

                var self = this;
                //$scope.product.two.data = {};
                $scope.product.two.data.dueTime = $scope.product.two.data.dueTime || '07';
            },
            clearFilter:function(){

                $scope.product.two.data = {
                    saleStatus:'',
                    dueTime:'07',
                    annualRevenue:'',
                    pPaymentInterestType:'',
                    pInvestType:'',
                    minimumAmount:'',
                    pSizeRatioType:'',
                    pBelongArea:''
                };
                $scope.isFilterSleTwo = false;
            },
            done: function () {

                var self = this;

                $scope.product[self.data.key].list = [];

                $scope.product[self.data.key].pager = {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                }

                $scope.$broadcast('scroll.infiniteScrollComplete');

                $timeout(function () {
                    $ionicScrollDelegate.$getByHandle(self.data.key).scrollTop();
                }, 50);

                self.hide();
                if(isSleFilter('two')){
                    $scope.isFilterSleTwo = true;
                }else {
                    $scope.isFilterSleTwo = false;
                }

            }
        });
        $faModal('zaiquanfilter', 'views/product/wap4_zaiquanFilter.html', $scope, {
            initialize: function () {

                var self = this;
                //$scope.product.three.data = {};
                $scope.product.three.data.dueTime = $scope.product.three.data.dueTime || '07';
            },
            clearFilter:function(){

                $scope.product.three.data = {
                    saleStatus:'',
                    dueTime:'07',
                    annualRevenue:'',
                    pPaymentInterestType:'',
                    pInvestType:'',
                    minimumAmount:'',
                    pSizeRatioType:'',
                    pBelongArea:''
                }
                $scope.isFilterSleThree = false;
            },
            done: function () {

                var self = this;

                $scope.product[self.data.key].list = [];

                $scope.product[self.data.key].pager = {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                }

                $scope.$broadcast('scroll.infiniteScrollComplete');

                $timeout(function () {
                    $ionicScrollDelegate.$getByHandle(self.data.key).scrollTop();
                }, 50);

                self.hide();
                if(isSleFilter('three')){
                    $scope.isFilterSleThree = true;
                }else {
                    $scope.isFilterSleThree = false;
                }

            }
        });

        $faModal('pevcfilter', 'views/product/wap4_pevcFilter.html', $scope, {
            initialize: function () {

                var self = this;
                //$scope.product.five.data = {};

            },
            clearFilter:function(){
                $scope.product.five.data= {
                        saleStatus:'',
                        minimumAmount:'05',
                        dueTime:'05',
                        rabateRatio:'04'
                }
                $scope.isFilterSleFive = false;
            },
            done: function () {

                var self = this;

                $scope.product[self.data.key].list = [];

                $scope.product[self.data.key].pager = {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                };

                $scope.$broadcast('scroll.infiniteScrollComplete');

                $timeout(function () {
                    $ionicScrollDelegate.$getByHandle(self.data.key).scrollTop();
                }, 50);

                self.hide();

                if($scope.product.five.data.saleStatus!='' || $scope.product.five.data.minimumAmount!='05'
                    || $scope.product.five.data.dueTime!='05' || $scope.product.five.data.rabateRatio!='04'
                ){
                    $scope.isFilterSleFive = true;
                }else {
                    $scope.isFilterSleFive = false;
                }
            }
        });

        $scope.goInform = function () {
            $faUser.info.isLogin ? $state.go('inform') : $rootScope.modal.login();
        };
        //打开筛选
        $scope.filterOpen = function (index) {

            var data = {};
            switch (index) {
                case 1:
                    data.key = 'one';
                    $scope.modal.xtfilter(data);

                    break;
                case 2:
                    data.key = 'two';
                    $scope.modal.zgfilter(data);

                    break;
                case 3:
                    data.key = 'three';
                    $scope.modal.zaiquanfilter(data);
                    break;
                case 4:
                    data.key = 'four';
                    $scope.modal.simufilter(data);
                    break;
                case 5:
                    data.key = 'five';
                    $scope.modal.pevcfilter(data);
                    break;
            }
        };
        //关闭筛选
        $scope.closeFilter = function (index) {
            $scope.isFilterSle = false;
            switch (index) {
                case 0:
                    $scope.xtfilter.hide();
                    break;
                case 1:
                    $scope.xtfilter.hide();
                    break;
                case 2:
                    $scope.zgfilter.hide();
                    break;
                case 3:
                    $scope.pevcfilter.hide();
                    break;
                case 4:
                    $scope.modal.simufilter(data);
                    break;
                case 5:
                    $scope.zaiquanfilter.hide();
                    break;
            }

        };

        $rootScope.$on('$stateChangeStart', function () {
            switch ($scope.index) {
                case 0:
                    if ($scope.xtfilter) {
                        $scope.xtfilter.hide();
                    }
                    break;
                case 1:
                    if ($scope.zgfilter) {
                        $scope.zgfilter.hide();
                    }
                    break;
                case 2:
                    if ($scope.pevcfilter) {
                        $scope.pevcfilter.hide();
                    }
                    break;
            }

        });
        $scope.goUpload = function () {
            var popTitle = '';
            var popButton = '';
            if (!$faUser.info.isLogin) {
                // 要登录
                $rootScope.modal.login();
            } else if ($faUser.isCertEmpty()) {
                popTitle = '您还未上传名片，上传并审核通过后才能上传产品';
                popButton = '去上传';
                pop();
            } else if ($faUser.isCertIng()) {
                popTitle = '您的名片还在审核中，审核通过后才能上传产品';
                popButton = '看名片';
                pop();
            } else if ($faUser.isCertDeny()) {
                popTitle = '您的名片审核失败，请重新上传';
                popButton = '去上传';
                pop();
            } else {
                $state.go('app.upload');
            }

            function pop() {
                var myPopup = $ionicPopup.show({
                    title: popTitle,
                    scope: $scope,
                    buttons: [
                        {
                            text: '取消',
                            type: 'confirmLoginCancel',
                            onTap: function (e) {
                                $state.go('product.prolist');
                            }
                        },
                        {
                            text: popButton,
                            type: 'button-positive confirmLogin',
                            onTap: function (e) {
                                $state.go('app.myself.certification', {repage: 'app.upload'});
                            }
                        }
                    ]
                });
            }
        }
        $scope.productAddToShop = function (pt, product) {
            if (product && pt) {
                var param = {productType: pt};
                if (pt != '01') {
                    param.productId = product.code;
                } else {
                    param.productId = product.id;
                }

                if (product.flagShop && product.flagShop == 'true') {
                    $faPopup.confirm({
                        title: '确定删除该产品？',
                        cancelText: '取消',
                        okText: '确定'
                    }, function (res) {
                        if (res) {
                            $faAPI.shops.productDeleteToShops(param).then(function (json) {
                                if (json) {
                                    if (!json.statusCode) {
                                       /* $faPopup.alert({
                                          title: '删除成功'
                                        });*/
                                        product.flagShop = '';
                                    }
                                }
                            });
                        }
                    });

                } else {
                    $faAPI.shops.productAddToShops(param).then(function (json) {
                        if (json) {
                            if (!json.statusCode) {
                                $faPopup.alert({
                                    title: '添加成功'
                                });
                                product.flagShop = 'true';
                            }
                        }
                    });
                }
            }
        }
    })
    .controller('shopsProductAdssdCtrl', function ($interval, $scope, $rootScope, $ionicHistory, $ionicGesture, $faMAP, $faAPI, $faUtil, $state, $faModal, $faPopup, $timeout, $ionicScrollDelegate, $stateParams, $faUser, $ionicPopup, $faPlatform) {
        $scope.platform = $faPlatform;

        $scope.issle = 1;
        $scope.sletype = 0;
        var sledivs, sletabview;

        sledivs = document.querySelectorAll('#slelist_add>div');
        sletabview = document.getElementById('sletabview');
        sledivs = angular.element(sledivs);
        sletabview = angular.element(sletabview);

        //$ionicGesture.on('swipeleft', function (e) {
        //  if ($scope.index == 3) { return }
        //  $ionicScrollDelegate.$getByHandle('mainScroll').scrollTo($scope.index * 100, 0);
        //
        //  $scope.index++;
        //  sleNav($scope.index);
        //  $scope.issle = 1;
        //  $scope.$digest();
        //
        //}, sletabview);
        //$ionicGesture.on('swiperight', function (e) {
        //
        //  if ($scope.index == 0) { return }
        //  $ionicScrollDelegate.$getByHandle('mainScroll').scrollTo($scope.index * 100 - 100, 0);
        //
        //  $scope.index--;
        //  sleNav($scope.index);
        //  $scope.issle = 1;
        //  $scope.$digest();
        //
        //}, sletabview);

        for (var i = 0; i < sledivs.length; i++) {
            sledivs[i].index = i;
            sledivs[i].onclick = function (e) {
                clearClass();
                this.className = 'w4-prolist-sle';
                //show(this.index);
                $scope.index = this.index;
                //初始化排序条件
                $scope.issle = 1;
                $scope.$digest();
                $scope.sletype = this.index;
            }
        }

        function clearClass() {
            //console.log('clearclass');
            for (var i = 0; i < sledivs.length; i++) {
                sledivs[i].className = '';
            }
        }

        function sleNav(index) {
            clearClass();
            //console.log(index);
            //console.log(sledivs[index]);
            sledivs[index].className = 'w4-prolist-sle';
        }

        $scope.scrollGoto = function (index) {
            $timeout(function () {
                $ionicScrollDelegate.$getByHandle('mainScroll').scrollTo(index * 100, 0);
            }, 50);
        };
        function switchTab() {
            console.log($scope.sletype);
            switch ($scope.sletype) {
                case 0:
                    $scope.index = 0;
                    sleNav($scope.index);
                    $scope.scrollGoto($scope.index);

                    break;
                case 1:
                    $scope.index = 1;
                    sleNav($scope.index);
                    $scope.scrollGoto($scope.index);

                    break;
                case 2:
                    $scope.index = 2;
                    sleNav($scope.index);
                    $scope.scrollGoto($scope.index);

                    break;
                case 3:
                    $scope.index = 3;
                    sleNav($scope.index);
                    $scope.scrollGoto($scope.index);
                    break;
                case 4:
                    $scope.index = 4;
                    sleNav($scope.index);
                    $scope.scrollGoto($scope.index);
                    break;
                default:
                    $scope.index = 0;
                    sleNav($scope.index);
                    $scope.scrollGoto($scope.index);
                    break;
            }
        }

        switchTab();

        //console.log($scope.index);
        $scope.product = {
            investType: $faMAP.investType,
            annualRevenue: $faMAP.annualRevenue,
            rabateRatio: $faMAP.rabateRatio,
            zero: {
                type: '01',
                data: {},
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: []
            },
            one: {
                type: '02',
                data: {},
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: []
            },
            two: {
                type: '03',
                data: {},
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: []
            },
            three: {
                type: '06',
                data: {},
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: []
            },
            four: {
                data: {},
                filter: {},
                pager: {
                    hasNaxtPage: true,
                    pageSize: 5,
                    nextPage: 1
                },
                list: []
            },
            five: {
                list: [],
                pager: true
            }
        };

        $scope.$on("$ionicView.enter", function () {
            //页面启动缓存时,其controller中不会反复执行，但会执行此监听-
            //用此来更新tab数据
            switchTab();

        });

        //加载更多
        $scope.loadMore = function (name) {

            if (name == 'one' || name == 'two') {
                $faUtil.extend($scope.product[name].data, {
                    pageSize: $scope.product[name].pager.pageSize,
                    type: $scope.product[name].type,
                    pageNo: $scope.product[name].pager.nextPage,
                    flagShopQuery: true
                });
                $faAPI.product.list($scope.product[name].data, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {

                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });

                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            }
            //股权基金
            if (name == 'three') {
                $faUtil.extend($scope.product[name].data, {
                    type: $scope.product[name].type,
                    pageSize: $scope.product[name].pager.pageSize,
                    pageNo: $scope.product[name].pager.nextPage,
                    flagShopQuery: true
                });

                $faAPI.product.pevcList($scope.product[name].data, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {
                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });
                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.$broadcast('scroll.infiniteScrollComplete');
                });
            }
            //阳光私募
            if (name == 'four') {
                $faUtil.extend($scope.product[name].data, {
                    pageSize: $scope.product[name].pager.pageSize,
                    pageNo: $scope.product[name].pager.nextPage,
                    flagShopQuery: true
                });
                $faAPI.product.simuList($scope.product[name].data, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {
                        item.lsjzJson = item.lsjzJson ? $faUtil.fromJson((item.lsjzJson).replace(/“/g, '"')) : '';
                        return item;
                    });

                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            }
        };

        //下拉刷新
        $scope.doRefresh = function (name) {
            if (name == 'one' || name == 'two') {
                //console.log($scope.product[name]);
                $scope.product[name].data = {};
                $scope.issle = 1;
                $faAPI.product.list({
                    pageSize: 5,
                    type: $scope.product[name].type,
                    pageNo: 1,
                    flagShopQuery: true
                }, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {

                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });
                    //删除之前的冗余数据
                    $scope.product[name].list = [];
                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    //console.log($scope.product[name]);
                    $scope.$broadcast('scroll.refreshComplete');
                });
            }
            //股权基金
            if (name == 'three') {
                $scope.issle = 1;
                $faAPI.product.pevcList({
                    type: $scope.product[name].type,
                    pageSize: 5,
                    pageNo: 1,
                    flagShopQuery: true
                }, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {
                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }

                        return item;
                    });
                    //删除之前的冗余数据
                    $scope.product[name].list = [];
                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.$broadcast('scroll.refreshComplete');
                });
            }
            //阳光私募
            if (name == 'four') {

                $faAPI.product.simuList({
                    pageSize: 5,
                    pageNo: 1,
                    flagShopQuery: true
                }, {
                    flag: false
                }).then(function (json) {

                    var list = json.list.map(function (item) {
                        item.lsjzJson = item.lsjzJson ? $faUtil.fromJson((item.lsjzJson).replace(/“/g, '"')) : '';
                        return item;
                    });
                    //删除之前的冗余数据
                    $scope.product[name].list = [];
                    $scope.product[name].list = $scope.product[name].list.concat(list);
                    $scope.product[name].pager = json.pager;
                    $scope.$broadcast('scroll.refreshComplete');

                });
            }
        };

        //返回顶部
        $scope.goTop = function (index) {
            $ionicScrollDelegate.scrollTop();
            $scope.scrollGoto(index);

        };
        //判断是否到达顶部隐藏
        $scope.getScrollPosition = function (name) {
            var scrollTop = $ionicScrollDelegate.$getByHandle(name).getScrollPosition().top;

            if (scrollTop < 200) {
                $scope.isTop = false;
            } else {
                $scope.isTop = true;
            }
            $scope.$digest();
        };
        $scope.goCertification = function ($event) {
            $event.stopPropagation();
            $faUser.info.isLogin ? $state.go('app.myself.certification') : $rootScope.modal.login();
            $scope.$watch('userRole', function (newValue) {
                //必须在此处初始化监听登录，否则会引发在其他地方登录了，导致此处监听错误。
                //表现为一进列表页会立即执行监听中的方法
                if (newValue) {
                    window.location.reload();
                }
            });
        };
        $scope.toView = function (type, id) {
            if (type && id) {
                var url = '';

                if (type == '01') {
                    url = 'product.simu';
                } else if (type == '02' || type == '03' || type == '07') {
                    url = 'product.xtzgdetail';
                } else if (type == '06') {
                    url = 'product.pevc';
                }

                $state.go(url, {id: id});
            } else {
                console.log('error,,');
            }
        };

        $scope.goInform = function () {
            $faUser.info.isLogin ? $state.go('inform') : $rootScope.modal.login();
        };

        $rootScope.$on('$stateChangeStart', function () {
            switch ($scope.index) {
                case 0:
                    if ($scope.xtfilter) {
                        $scope.xtfilter.hide();
                    }
                    break;
                case 1:
                    if ($scope.zgfilter) {
                        $scope.zgfilter.hide();
                    }
                    break;
                case 2:
                    if ($scope.pevcfilter) {
                        $scope.pevcfilter.hide();
                    }
                    break;
            }
        });

        $scope.productAddToShop = function (pt, product) {
            if (product && pt) {
                var param = {productType: pt};
                if (pt != '01') {
                    param.productId = product.code;
                } else {
                    param.productId = product.id;
                }

                if (product.flagShop && product.flagShop == 'true') {
                    $faPopup.confirm({
                        title: '确定删除该产品？',
                        cancelText: '取消',
                        okText: '确定'
                    }, function (res) {
                        if (res) {
                            $faAPI.shops.productDeleteToShops(param).then(function (json) {
                                if (json) {
                                    if (!json.statusCode) {
                                        //$faPopup.alert({
                                        //  title: '删除成功'
                                        //});
                                        product.flagShop = '';
                                    }
                                }
                            });
                        }
                    });

                } else {
                    $faAPI.shops.productAddToShops(param).then(function (json) {
                        if (json) {
                            if (!json.statusCode) {
                                $faPopup.alert({
                                    title: '添加成功'
                                });
                                product.flagShop = 'true';
                            }
                        }
                    });
                }
            }
        }
    })
    .controller('shopsDataHomeCtrl', function ($scope, $faAPI, $faUser) {
        var sphone = $faUser.info.mobile;
        $faAPI.shops.ShopViewCount({
            shopId: sphone
        }).then(function (json) {
            $scope.shopCount = json;
        });

        $faAPI.shops.ShopProductRecord({
            pageNo: 1,
            pageSize: 5,
            shopId: sphone
        }).then(function (json) {
            console.log(json.list);
            $scope.shopPro = json.list;
            $scope.totalCount = json.pager.totalCount;
        });
    })
    .controller('shopsDataListCtrl', function ($scope, $faAPI, $faUser) {
        var sphone = $faUser.info.mobile;
        $scope.shopProList = [];
        $scope.pager = {
            pageSize: 10,
            pageNo: 1,
            hasNaxtPage: true
        };
        $scope.loadMore = function () {

            $faAPI.shops.ShopProductRecord({
                pageNo: $scope.pager.pageNo,
                pageSize: $scope.pager.pageSize,
                shopId: sphone
            }).then(function (json) {

                $scope.shopProList = $scope.shopProList.concat(json.list);
                $scope.pager.pageNo = json.pager.nextPage;
                $scope.pager.hasNaxtPage = json.pager.hasNaxtPage;
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
        };

    })
    .controller('shopsDataDetailCtrl', function ($scope, $faAPI, $faUser, $stateParams) {
        var sphone = $faUser.info.mobile;
        var param = $stateParams.param;
        $scope.type = $stateParams.type;

        switch ($scope.type) {
            //信托：110201
            //资管：110202
            //pevc：110203
            //阳光私募：110204
            case '110201':
                $scope.ptype = '02';
                break;

            case '110202':
                $scope.ptype = '03';
                break;
            case '110203':
                $scope.ptype = '06';
                break;
            case '110204':
                $scope.ptype = '01';
                break;
            default:
                $scope.ptype = '02';
                console.log('缺少typeid');
        }

        $scope.pager = {
            hasNaxtPage: true,
            pageNo: 1,
            pageSize: 10
        };

        $faAPI.shops.ShopProductRecordDetail({
            pageNo: $scope.pager.pageNo,
            pageSize: $scope.pager.pageSize,
            shopId: sphone,
            type: $scope.type,
            param: param

        }).then(function (json) {
            $scope.p = json.dto;
            $scope.visitorList = json.list;
            $scope.pager = json.pager;
            if ($scope.p.expectSaleAmount != 0) {
                $scope.p.process = (($scope.p.allSubscriptionAmount * 100 / $scope.p.expectSaleAmount).toFixed(2) > 100) ?
                    100 :
                    ($scope.p.allSubscriptionAmount * 100 / $scope.p.expectSaleAmount).toFixed(2);
            } else {
                $scope.p.process = 0;
            }
        });

    })

    .controller('previewListCtrl', function ($scope, $faAPI, $stateParams, $state, $faUtil) {

        $scope.pager = {
            pageSize: 10,
            pageNo: 1,
            hasNaxtPage: true,
            loginName: $stateParams.sphone
        };
        $scope.shoproducts = [];
        $scope.uid = $stateParams.uid;
        $scope.loadMore = function () {
            $faAPI.shops.list($scope.pager).then(function (json) {
                var list = json.list.map(function (item) {
                    if (item.fpFundInfoDTO) {
                        item.fpFundInfoDTO.lsjzJson = item.fpFundInfoDTO.lsjzJson ? $faUtil.fromJson((item.fpFundInfoDTO.lsjzJson).replace(/“/g, '"')) : '';
                    } else if (item.productDTO) {
                        if (item.productDTO.expectSaleAmount != 0) {
                            item.productDTO.process = ((item.productDTO.allSubscriptionAmount * 100 / item.productDTO.expectSaleAmount).toFixed(2) > 100) ?
                                100 :
                                (item.productDTO.allSubscriptionAmount * 100 / item.productDTO.expectSaleAmount).toFixed(2);
                        } else {
                            item.productDTO.process = 0;
                        }
                    }
                    return item;
                });
                $scope.shoproducts = $scope.shoproducts.concat(list);

                $scope.pager.pageNo = json.pager.nextPage;
                $scope.pager.hasNaxtPage = json.pager.hasNaxtPage;
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
        };

        $scope.toView = function (type, id) {

            if (type && id) {
                var url = '';

                if (type == '01') {
                    url = 'product.simu';
                } else if (type == '02' || type == '03' || type == '07') {
                    url = 'product.shopxtzgdetail';
                } else if (type == '06') {
                    url = 'product.shoppevc';
                }

                $state.go(url, {id: id, share: 'true', sharePhone: $stateParams.sphone});
            } else {
                console.log('error,,');
            }

        };

    })

    .controller('shopSaySayCtrl', function ($scope, $faAPI, $stateParams, $rootScope) {

        $scope.baseUrl = reqUrl;
        $scope.pager = {
            pageSize: 10,
            pageNo: 1,
            hasNaxtPage: true,
            loginName: $stateParams.sphone
        };

        $scope.list = [];

        $scope.loadMore = function () {
            $faAPI.shops.shopUserSaySay($scope.pager).then(function (json) {
                $scope.list = $scope.list.concat(json.list);

                $scope.pager.pageNo = json.pager.nextPage;
                $scope.pager.hasNaxtPage = json.pager.hasNaxtPage
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
        }
    })
    .controller('shopsIndexCtrl', function ($scope, $faAPI, $stateParams, $faUser, $faPlatform, $interval, $lfShare, $location) {
        $scope.platform = $faPlatform;
        $scope.hasMessage;
        var shareName = $faUser.info.realName ? '【' + $faUser.info.realName + '】' : '';
        var data = {
            title: '金策师',
            desc: '您的理财师' + shareName + '为您推荐了新产品，点击查看',
            link: $location.protocol() + '://' + $location.host() + '/#/shoPreview?share=true&sphone=' + $faUser.info.mobile,
            imgUrl: 'http://lec.superfa.cn/upload/bann/20161208/1481164249317854085.png'
        };

        //h5微信分享成功后的统计
        function h5shareStatis() {

            var reqData = {
                type: '110400',
                host: $location.host(),
                path: $location.path(),
                param: $location.search(),
                source: 'WAP',
                shopId: $faUser.info.mobile,
                userId: $faUser.info.mobile
            };
            $faAPI.shops.statis({
                type: 'statisitics',
                data: reqData
            }).then(function (json) {
            });
        }

        window.shareCallBack = function () {
            h5shareStatis();
        }
        //微信分享
        $lfShare.wechatShare(data, h5shareStatis);
        //分享

        if( $faUser.info.mobile == undefined){
            $faUser.info.mobile = 0;
        }
        $scope.proshare = function () {
            data.link = reqUrl + '/#/shoPreview?share=true&sphone=' + $faUser.info.mobile;
            if ($faPlatform.androidAPP) {
                h5shareStatis()
                document.addEventListener("deviceready", OnDeviceReady, false);
                function OnDeviceReady() {
                    cordova.exec(null, null, "MyPlugin", "toShare", [data.title, data.desc, data.link, data.imgUrl]);
                }
            } else {
                productShare(data.title, data.desc, data.link, data.imgUrl);
            }
            //APP分享统计
            //h5shareStatis();
        };
        //融云IOS SDK登录，调起界面
        if($faPlatform.IOSAPP){
            //$faAPI.shops.ryToken().then(function(data){
            //    //初始化
            //    loginRongyun(data.token);
            //});
            $scope.goIOS = function(){
                mychatlist();
            }
        }
        //h5端检查未读
        $faAPI.shops.ryToken().then(function(data){
            console.log('检查未读');
            //公有云初始化
            RongIMLib.RongIMClient.init(CHAT_APPKEY);
            //instance = RongIMClient.getInstance();

            //此接口必须在init()方法之后，连接融云服务器 connect 之前调用。
            RongIMClient.getInstance().hasRemoteUnreadMessages(data.token,{
                onSuccess:function(hasMessage){
                    if(hasMessage){
                        // 有未读的消息
                        console.log('是否有未读消息');
                        console.log(hasMessage);
                        $scope.hasMessage = true;

                    }else{
                        // 没有未读的消息
                        console.log('是否有未读消息');
                        console.log(hasMessage);
                        $scope.hasMessage = false;
                    }
                },onError:function(err){
                    // 错误处理...
                    console.log('获取未读消息错误');
                    $scope.hasMessage = false;
                }
            });


        });

    })

    .controller('visitorListCtrl', function ($interval, $scope,$location, $rootScope, $ionicHistory, $ionicGesture, $faMAP, $faAPI, $faUtil, $state, $faModal, $faPopup, $timeout, $ionicScrollDelegate, $stateParams, $faUser, $ionicPopup, $faPlatform) {
        $scope.phone = $faUser.info.mobile;
        $scope.addCust = function (weixinAppid) {
            $state.go('addClient', {weixinAppid:weixinAppid})

            //埋点统计
            var reqData = {
                type: '110601',
                host: $location.host(),
                path: $location.path(),
                param: $location.search(),
                source: 'WAP',
                shopId: $faUser.info.mobile
            };
            $faAPI.shops.statis({
                type: 'statisitics',
                data: reqData
            }).then(function (json) {
            });
        }

        $rootScope.isCusvisit = false;
        // console.log( $scope.phone = $stateParams.sphone)
        $scope.index = 0;


        //function defaultNone(){
        //    console.log('defaultNone');
        //    var default1 = window.document.getElementById('default-none-1');
        //    if($scope.visitorList.length<=0 ){
        //        default1.style.display = 'block';
        //    }
        //    var default2 = window.document.getElementById('default-none-2');
        //    if($scope.clientList.length<=0 ){
        //        default2.style.display = 'block';
        //    }
        //}

        $scope.$on("$ionicView.enter", function () {
            //页面启动缓存时,其controller中不会反复执行，但会执行此监听-



            $scope.visitorPager = {
                'pageSize': 10,
                'pageNo': 1,
                'hasNaxtPage': true
            };
            $scope.clientPager = {
                'pageSize': 10,
                'pageNo': 1,
                'hasNaxtPage': true
            };
            $faAPI.shops.visitorList($scope.visitorPager).then(function (json) {
                $scope.visitorList = [];
                $scope.visitorList = $scope.visitorList.concat(json.list);
                $scope.visitorPager.hasNaxtPage = json.pager.hasNaxtPage;
                $scope.visitorPager.pageNo = json.pager.nextPage;

                $scope.$broadcast('scroll.infiniteScrollComplete');
                //defaultNone();
            });
            $faAPI.shops.clientList($scope.clientPager).then(function (json) {
                $scope.clientList = [];
                $scope.clientList = $scope.clientList.concat(json.list);

                $scope.clientPager.hasNaxtPage = json.pager.hasNaxtPage;
                $scope.clientPager.pageNo = json.pager.nextPage;

                $scope.$broadcast('scroll.infiniteScrollComplete');
                //defaultNone();

            })
            //进入客户管理页埋点统计
            function btnShareStatis() {
                console.log("统计")
                console.log($rootScope.shopUserPhone)

                var reqData = {
                    type: '110600',
                    host: $location.host(),
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP',
                    shopId:  $rootScope.shopUserPhone
                };
                $faAPI.shops.statis({
                    type: 'statisitics',
                    data: reqData
                }).then(function (json) {
                });
            }
            setTimeout(function(){
                btnShareStatis();
            }, 800)

        });


        //加载更多
        $scope.loadMore = function () {
            if ($scope.index == 0) {
                $faAPI.shops.visitorList($scope.visitorPager).then(function (json) {
                    $scope.visitorList = $scope.visitorList.concat(json.list);

                    $scope.visitorPager.hasNaxtPage = json.pager.hasNaxtPage;
                    $scope.visitorPager.pageNo = json.pager.nextPage;

                    $scope.$broadcast('scroll.infiniteScrollComplete');
                    //defaultNone();
                })
            } else if ($scope.index == 1) {
                $faAPI.shops.clientList($scope.clientPager).then(function (json) {
                    $scope.clientList = $scope.clientList.concat(json.list);

                    $scope.clientPager.hasNaxtPage = json.pager.hasNaxtPage;
                    $scope.clientPager.pageNo = json.pager.nextPage;

                    $scope.$broadcast('scroll.infiniteScrollComplete');
                    //defaultNone();
                })
            }

        }

        var tabBox = angular.element(document.querySelectorAll('#tabSlelist div'));
        var tabItemBox = angular.element(document.querySelector('#visitorTabContent'));

        //$ionicGesture.on('swipeleft',function(e){
        //  if ($scope.index >= 1) { return };
        //  $scope.index = 1;
        //  updataClass($scope.index);
        //  $scope.$apply();
        //},tabItemBox);
        //$ionicGesture.on('swiperight',function(e){
        //  if( $scope.index <= 0) { return };
        //  $scope.index = 0;
        //  updataClass($scope.index);
        //  $scope.$apply();
        //},tabItemBox);

        for (var i = 0; i < tabBox.length; i++) {
            tabBox[i].index = i;
            tabBox[i].onclick = function () {
                updataClass(this.index);
                $scope.index = this.index;
                //defaultNone();
                $scope.$apply();
            }
        }
        ;
        function updataClass(e) {
            $ionicScrollDelegate.$getByHandle('mainScroll').scrollTo($scope.index * 100, 0);
            for (var i = 0; i < tabBox.length; i++) {
                tabBox[i].className = 'text-center';
            }
            ;
            tabBox[e].className = 'text-center active';
        };
    })
    .controller('visitorDetailCtrl', function ($interval, $scope, $rootScope, $ionicHistory, $ionicGesture, $faMAP, $faAPI, $faUtil, $state, $faModal, $faPopup, $timeout, $ionicScrollDelegate, $stateParams, $faUser, $ionicPopup, $faPlatform) {
        $scope.weixinAppid = $stateParams.weixinAppid;

        $scope.pager = {
            weixinAppid: $scope.weixinAppid,
            pageSize: 10,
            pageNo: 1,
            hasNaxtPage: true
        }

        $scope.list = [];

        $scope.loadMore = function () {
            $faAPI.shops.visitorDetail($scope.pager).then(function (json) {
                $scope.list = $scope.list.concat(json.list);
                $scope.userInfo = json.userInfo;

                $scope.pager.pageNo = json.pager.nextPage;
                $scope.pager.hasNaxtPage = json.pager.hasNaxtPage;

                $scope.$broadcast('scroll.infiniteScrollComplete');

            });
        }

        if($faPlatform.IOSAPP){
            $scope.goioschat = function(tid,name){
                console.log(tid);
                mychat(tid,name)

            }
        }
        if($faPlatform.androidAPP){
            $scope.goioschat = function(tid,name){
                console.log('调用安卓goioschat');
                document.addEventListener("deviceready", OnDeviceReady, false);
                function OnDeviceReady() {
                    cordova.exec(null, null, "MyPlugin", "mychat", [tid,name]);
                }
            }
        }

    })
    .controller('clientDetailCtrl', function ($interval, $scope, $rootScope, $ionicHistory, $ionicGesture, $faMAP, $faAPI, $faUtil, $state, $faModal, $faPopup, $timeout, $ionicScrollDelegate, $stateParams, $faUser, $ionicPopup, $faPlatform, $ionicModal) {
        $scope.id = $stateParams.id;
        $scope.client = {
            id: $scope.id
        };

        $faAPI.shops.clientDetail({id: $scope.id}).then(function (json) {
            $scope.detail = json.dto;
        });


        $scope.delete = function () {
            $faPopup.confirm({
                title: '确认删除',
                buttons: [
                    {
                        'text': '取消'
                    },
                    {
                        'text': '确定',
                        'type': 'bg-red',
                        'onTap': function (e) {
                            $faAPI.shops.deleteClient({id: $scope.id}).then(function (json) {
                                $state.go('visitorList', {index: 1});
                            })
                        }
                    }
                ]
            })
        }

        $ionicModal.fromTemplateUrl('views/shops/visitor/edit.html', {
            scope: $scope,
            animation: 'slide-in-up',
            backdropClickToClose: false,
            pingji: function(index) {
                $scope.client.starlevel = index;
            },
            editShow: function (e) {
                $scope.aloneItem = e;
                switch (e) {
                    case 'name' :
                        $scope.editTitle = '姓名'
                        break;
                    case 'remark' :
                        $scope.editTitle = '备注'
                        break;
                    case 'mobile' :
                        $scope.editTitle = '手机'
                        break;
                    case 'email' :
                        $scope.editTitle = '邮箱'
                        break;
                    case 'companyName' :
                        $scope.editTitle = '公司'
                        break;
                    case 'profession' :
                        $scope.editTitle = '职位'
                    case 'starlevel' :
                        $scope.editTitle = '用户等级'
                        break;
                }
                $scope.client[e] = $scope.detail[e];
                console.log($scope.detail[e])
                this.show();
            },
            done: function () {
                if ($scope.aloneItem == 'name' && !$scope.client.name) {
                    $faPopup.alert({
                        title: '姓名不能为空'
                    });
                } else if ($scope.client.mobile && !(/^1[34578]\d{9}$/.test($scope.client.mobile))) {
                    $faPopup.alert({
                        title: '请输入正确手机号'
                    });
                } else if ($scope.client.email && !(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($scope.client.email))) {
                    $faPopup.alert({
                        title: '请输入正确邮箱'
                    });
                } else {
                    this.hide();
                    $faAPI.shops.updateClient($scope.client).then(function (json) {
                        $faAPI.shops.clientDetail({id: $scope.id}).then(function (json) {
                            $scope.detail = json.dto;
                        });
                    });
                }
            }
        }).then(function (modal) {
            $scope.edit = modal;
        });
    })
    .controller('addClientCtrl', function ($interval, $scope, $rootScope, $ionicHistory, $ionicGesture, $faMAP, $faAPI, $faUtil, $state, $faModal, $faPopup, $timeout, $ionicScrollDelegate, $stateParams, $faUser, $ionicPopup, $faPlatform) {


        $scope.weixinAppid = $stateParams.weixinAppid || '';
        //$scope.id = $stateParams.id || '';

        $scope.client = {};
        $scope.index = 1;

        if ($scope.weixinAppid) {
            $scope.index = 0;
            $scope.client.weixinAppid = $scope.weixinAppid;
            $faAPI.shops.clientDetail({weixinAppid: $scope.weixinAppid}).then(function (json) {
                $scope.weChatInfo = json.dto;
                $scope.client.name = json.dto.nickname;
            })
        }
        ;

        $scope.pingji =function(index) {
            $scope.client.starlevel = index;
        }

        $scope.save = function () {
            if (!$scope.client.name) {
                $faPopup.alert({
                    title: '请输入姓名'
                });
            } else if ($scope.client.mobile && !(/^1[34578]\d{9}$/.test($scope.client.mobile))) {
                $faPopup.alert({
                    title: '请输入正确手机号'
                });
            } else if ($scope.client.email && !(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($scope.client.email))) {
                $faPopup.alert({
                    title: '请输入正确邮箱'
                });
            } else {
                $faAPI.shops.addClient($scope.client).then(function (json) {
                    $ionicPopup.alert({
                        title: '添加成功',
                        buttons: [{
                            'text': '确定',
                            'type': 'button-positive'
                        }]
                    }).then(function () {
                        $state.go('visitorList', {'index': $scope.index});
                    })
                })
            }
        }
    })
    .controller('shopsAcListCtrl', function ($scope, $stateParams,$filter, $timeout, $faPopup, $faModal, $faAPI, $faMAP, $faUploader, $faPlatform, $state) {
        $scope.baseUrl = reqUrl;
        $scope.sphone = $stateParams.sphone;
        $scope.shopsActivity = $faMAP.shopsActivity;

        $scope.reqData = {
            activityType: '1'
        };

        $scope.date = {};

        $faModal('addShopAc', 'views/shops/activity/addShopAc.html', $scope, {

            initialize: function () {
                $scope.reqData = {
                    activityTitle: '',
                    activityStartDateStr: '',
                    activityEndDateStr: '',
                    activityPrice:'',
                    activityDesc:'',
                    activityPriceDescribe:'',
                    activityPrice:''
                }
                $scope.date = {
                    begin:'',
                    end : ''
                }
                var self = this;
                $timeout(function () {
                    var t = document.getElementById('acfile');
                    t.addEventListener('change', function (e) {
                        doUpload(e);
                    });
                }, 500);

            },
            done: function () {

                var self = this;

                if (!$scope.reqData.activityTitle) {
                    $faPopup.alert({
                        title: '请输入活动名称'
                    });
                    return;
                }
                if(!$scope.reqData.activityType){
                    $faPopup.alert({
                        title:'请选择活动类型'
                    })
                }
                if (!$scope.date.begin) {
                    $faPopup.alert({
                        title: '请选择开始时间'
                    });
                    return;
                } else {
                    $scope.reqData.activityStartDateStr = $filter("date")($scope.date.begin, "yyyy-MM-dd HH:mm:ss");
                }
                if (!$scope.date.end) {
                    $faPopup.alert({
                        title: '请选择结束时间'
                    });
                    return;
                } else {
                    $scope.reqData.activityEndDateStr = $filter("date")($scope.date.end, "yyyy-MM-dd HH:mm:ss");
                }
                var ttimes = $filter("date")($scope.date.begin, "yyyy/MM/dd HH:mm");
                var ttimee = $filter("date")($scope.date.end, "yyyy/MM/dd HH:mm");
                if ((new Date(ttimes)) > (new Date(ttimee))) {
                    $faPopup.alert({
                        title: '开始时间不能大于结束时间'
                    });
                    return;
                }
                if((new Date(ttimes)).getTime() == (new Date(ttimee)).getTime()) {
                    $faPopup.alert({
                        title: '开始时间不能等于结束时间'
                    });
                    return;
                }
                if ($scope.reqData.activityType == '1' && !$scope.reqData.activityAddress) {
                    $faPopup.alert({
                        title: '请输入活动地址'
                    });
                    return;
                }

                if($scope.reqData.activityPrice) {
                    var reg = /^([1-9]\d*|[0]{1,1})$/;
                    if(!reg.test($scope.reqData.activityPrice)){
                        $faPopup.alert({
                            title: '活动费用必须为非负整数'
                        });
                        return;
                    }
                }
                if (!$scope.reqData.activityDesc) {
                    $faPopup.alert({
                        title: '请输入活动描述'
                    });
                    return;
                }

                $faAPI.shops.addFpClientActivity($scope.reqData).then(function (json) {
                    console.log(json)
                    $scope.addShopAc.hide();
                    loadDate();
                });
            }
        });



        $scope.list = [];
        $scope.page = {
            mobile:$stateParams.sphone
        };

        loadDate = function () {
            $faAPI.shops.activityList($scope.page).then(function (json) {
                if (json) {
                    $scope.list = json.list;
                    console.log( $scope.list)
                    angular.forEach($scope.list, function (o, i) {
                        if (o.activityEndDate) {
                            var ttime = $filter("date")(o.activityEndDateTime, "yyyy/MM/dd HH:mm");
                            if ((new Date(ttime)) > (new Date())) {
                                o.activityOver = false;
                            } else {
                                o.activityOver = true;
                            }
                        }
                    });

                    $scope.page = json.pager;

                }

            });
        }
        loadDate();

        $scope.delete = function (id) {
            if (id) {
                $faPopup.confirm({
                    title: '确认删除吗',
                    buttons: [
                        {
                            'text': '取消'
                        },
                        {
                            'text': '确定',
                            'type': 'bg-red',
                            'onTap': function (e) {
                                $faAPI.shops.activityDelete({id: id}).then(function (json) {
                                    loadDate();
                                })
                            }
                        }
                    ]
                });
            }
        }

        function doUpload(e) {
            var files = e.target.files;
            var fileSize = files[0].size;

            if (!$faMAP.regular.image.test(files[0].type)) {
                $faPopup.alert({
                    title: '上传的文件格式不对'
                });
                return;
            } else if (fileSize > 5242880) {
                $faPopup.alert({
                    title: '上传的文件太大了'
                });
                return;
            }

            $faUploader.removeAll();
            $faUploader.addFiles(files);
            $scope.files = $faUploader.getFiles();

            var baseUrl = '';
            if (!$faPlatform.IOSAPP && !$faPlatform.androidAPP) {
                baseUrl = fileUploadUrl;
            } else {
                baseUrl = reqUrl + fileUploadUrl;
            }

            $faUploader.startUpload({
                url: baseUrl,
                concurrency: 2,
                onProgress: function () {
                },
                onCompleted: function (file, res) {
                    var res = angular.fromJson(res);

                    if (res.statusCode === '0000') {
                        var uri = res.attributes.fileUrl;
                        $scope.reqData.activityImg = uri;
                    } else {
                        $faPopup.alert({
                            title: $faMAP.statusCode[res.statusCode]
                        });
                    }
                    $scope.$apply();
                }

            });
        }

        $scope.wid = Math.ceil(window.innerWidth/8)*5
        console.log($scope.wid)
        $scope.myObj = {

            "height": $scope.wid + 'px'
        }


        // $scope.imgheig = .height()
        // console.log($('.aclist_list_i img'))

        $scope.imghe = function(index){
        var _img =  document.getElementById('shopaclist'+index)
            // _img.style.top = -Math.ceil(_img.height/2) - $scope.wid/2 + 'px'
            if((_img.height - $scope.wid)>0){
                _img.style.top = -Math.ceil((_img.height - $scope.wid)/2) + 'px'
            }
            if((_img.height - $scope.wid)<0){
                _img.style.minHeight = $scope.wid +'px';
                _img.style.top = -Math.ceil((_img.height - $scope.wid)/2) + 'px'
            }

            // e.$$nextSibling.$index


             // return Math.ceil(e.$index.height/2) - $scope.wid/2 + 'px'

        }

    })
    .controller('shopsAcDetailCtrl', function ($scope, $filter, $stateParams,$ionicPopup, $state, $timeout, $faPopup, $faModal, $faAPI, $faMAP, $faUploader, $faPlatform, $faUser, $location, $lfShare) {
        $scope.baseUrl = reqUrl;

        $scope.id = $stateParams.id;
        $scope.sphone = $stateParams.sphone;
        console.log();
        $scope.dto = {};
        $scope.reqData = {};
        $scope.date = {};
        var data = {};

        loadDetail = function () {
            $faAPI.shops.activityDetail({id: $scope.id}).then(function (json) {
                console.log(json)
                if (json) {
                    $scope.dto = json.dto;
                    $scope.reqData = angular.copy($scope.dto);

                    //微信分享
                    data = {
                        title: $scope.dto.activityTitle,
                        desc: $scope.dto.activityDesc,
                        link: $location.protocol() + '://' + $location.host() + '/#/shops/previewAcDetail/' + $faUser.info.mobile + '/' + $scope.id + '?share=true&sphone=' + $faUser.info.mobile,
                        imgUrl: 'https://www.superfa.cn/upload/bann/20170117/1484640777250263637.png'
                    };
                    $lfShare.wechatShare(data);
                }
            });
        }

        if ($scope.id) {
            loadDetail();
        }

        $scope.delete = function (id) {
            if ($scope.dto.id) {
                $faPopup.confirm({
                    title: '确认删除吗',
                    buttons: [
                        {
                            'text': '取消'
                        },
                        {
                            'text': '确定',
                            'type': 'bg-red',
                            'onTap': function (e) {
                                $faAPI.shops.activityDelete({id: $scope.dto.id}).then(function (json) {
                                    $state.go('app.shopsAcList', {reload: true});
                                })
                            }
                        }
                    ]
                });
            }
        }

        $faModal('addShopAc', 'views/shops/activity/addShopAc.html', $scope, {
            initialize: function () {
                var self = this;

                if ($scope.reqData.activityStartDateTime) {
                    $scope.date.begin = new Date($filter("date")($scope.reqData.activityStartDateTime, "yyyy/MM/dd HH:mm"));
                }
                if ($scope.reqData.activityEndDateTime) {
                    $scope.date.end = new Date($filter("date")($scope.reqData.activityEndDateTime, "yyyy/MM/dd HH:mm"));
                }

                if ($scope.reqData.activityEndDate) {
                    delete $scope.reqData.activityEndDate;
                }
                if ($scope.reqData.activityStartDate) {
                    delete $scope.reqData.activityStartDate;
                }
                if ($scope.reqData.activityEndDateTime) {
                    delete $scope.reqData.activityEndDateTime;
                }
                if ($scope.reqData.activityStartDateTime) {
                    delete $scope.reqData.activityStartDateTime;
                }
                if ($scope.reqData.createBy) {
                    delete $scope.reqData.createBy;
                }
                if ($scope.reqData.createDate) {
                    delete $scope.reqData.createDate;
                }
                if ($scope.reqData.updateBy) {
                    delete $scope.reqData.updateBy;
                }
                if ($scope.reqData.updateDate) {
                    delete $scope.reqData.updateDate;
                }

                $timeout(function () {
                    var t = document.getElementById('acfile');
                    t.addEventListener('change', function (e) {
                        doUpload(e);
                    });
                }, 500);
            },
            done: function () {
                var self = this;

                if (!$scope.reqData.activityTitle) {
                    $faPopup.alert({
                        title: '请输入活动名称'
                    });
                    return;
                }
                if (!$scope.date.begin) {
                    $faPopup.alert({
                        title: '请选择开始时间'
                    });
                    return;
                } else {
                    $scope.reqData.activityStartDateStr = $filter("date")($scope.date.begin, "yyyy-MM-dd HH:mm:ss");
                }
                if (!$scope.date.end) {
                    $faPopup.alert({
                        title: '请选择结束时间'
                    });
                    return;
                } else {
                    $scope.reqData.activityEndDateStr = $filter("date")($scope.date.end, "yyyy-MM-dd HH:mm:ss");
                }

                var ttimes = $filter("date")($scope.date.begin, "yyyy/MM/dd HH:mm");
                var ttimee = $filter("date")($scope.date.end, "yyyy/MM/dd HH:mm");
                if ((new Date(ttimes)) > (new Date(ttimee))) {
                    $faPopup.alert({
                        title: '开始时间不能大于结束时间'
                    });
                    return;
                }
                if ($scope.reqData.activityType == '1' && !$scope.reqData.activityAddress) {
                    $faPopup.alert({
                        title: '请输入活动地址'
                    });
                    return;
                }
                if (!$scope.reqData.activityDesc) {
                    $faPopup.alert({
                        title: '请输入活动描述'
                    });
                    return;
                }

                $faAPI.shops.activityUpdate($scope.reqData).then(function (json) {
                    $scope.addShopAc.hide();
                    loadDetail();
                });
            }
        });


        function doUpload(e) {
            var files = e.target.files;
            var fileSize = files[0].size;

            if (!$faMAP.regular.image.test(files[0].type)) {
                $faPopup.alert({
                    title: '上传的文件格式不对'
                });
                return;
            } else if (fileSize > 5242880) {
                $faPopup.alert({
                    title: '上传的文件太大了'
                });
                return;
            }

            $faUploader.removeAll();
            $faUploader.addFiles(files);
            $scope.files = $faUploader.getFiles();

            var baseUrl = '';
            if (!$faPlatform.IOSAPP && !$faPlatform.androidAPP) {
                baseUrl = fileUploadUrl;
            } else {
                baseUrl = reqUrl + fileUploadUrl;
            }

            $faUploader.startUpload({
                url: baseUrl,
                concurrency: 2,
                onProgress: function () {
                },
                onCompleted: function (file, res) {
                    var res = angular.fromJson(res);

                    if (res.statusCode === '0000') {
                        var uri = res.attributes.fileUrl;
                        $scope.reqData.activityImg = uri;

                        console.log($scope.reqData.activityImg);
                    } else {
                        $faPopup.alert({
                            title: $faMAP.statusCode[res.statusCode]
                        });
                    }
                    $scope.$apply();
                }

            });
        }

        $scope.showPopup = function () {
            $scope.data = {
                activityId: $scope.id
            };

            var myPopup = $ionicPopup.show({
                template: '<input type="text" ng-model="data.userName" placeholder="姓名"><div style="width: 100%;height: 1px;border-bottom: 1px solid #eee;margin: 0 -10px;position: absolute;"></div><input type="text" ng-model="data.userPhone" placeholder="手机" maxlength="11" style="margin-top: 10px;">',
                title: '活动报名',
                scope: $scope,
                buttons: [
                    {text: '取消'},
                    {
                        text: '确定',
                        type: 'bg-red',
                        onTap: function (e) {
                            if (!$scope.data.userName || !$scope.data.userPhone) {
                                e.preventDefault();
                            } else {
                                if (!/^1\d{10}$/.test($scope.data.userPhone)) {
                                    $faPopup.alert({
                                        title: ' 手机号码格式错误'
                                    });
                                    e.preventDefault();
                                    return;
                                }
                                return $scope.data;
                            }
                        }
                    }
                ]
            });

            myPopup.then(function (res) {
                if (res) {
                    $faAPI.shops.activityAddPerson(res).then(function (json) {
                        if (json) {
                            $faPopup.alert({
                                title: '报名成功'
                            });
                        }
                    });
                }
            });
        };

        //分享
        $scope.proshare = function () {
            data.link = reqUrl + '/#/shops/previewAcDetail/' + $faUser.info.mobile + '/' + $scope.id + '?share=true&sphone=' + $faUser.info.mobile;
            if ($faPlatform.androidAPP) {
                document.addEventListener("deviceready", OnDeviceReady, false);
                function OnDeviceReady() {
                    cordova.exec(null, null, "MyPlugin", "toShare", [data.title, data.desc, data.link, data.imgUrl]);
                }
            } else {
                productShare(data.title, data.desc, data.link, data.imgUrl);
            }
        };
    })
    .controller('shopsCheckApplyCtrl', function ($scope, $filter, $stateParams, $state, $timeout, $faPopup, $faModal, $faAPI, $faMAP, $faUploader, $faPlatform) {
        $scope.id = $stateParams.id;

        $scope.list = [];
        $scope.page = {};

        if ($scope.id) {
            $faAPI.shops.activityPerson({activityId: $scope.id}).then(function (json) {
                if (json) {
                    $scope.list = json.list;
                    $scope.page = json.pager;
                }
            });
        }
    })
    .controller('shopsPreviewAcListCtrl', function ($scope, $filter, $timeout, $faPopup, $faModal, $faAPI, $faMAP, $faUploader, $faPlatform, $state, $stateParams, $location) {
        $scope.baseUrl = reqUrl;

        $scope.sphone = $stateParams.sphone;

        //if (!$scope.sphone) {
        //    $state.go('/');
        //    return;
        //}

        $scope.list = [];
        $scope.page = {
            mobile: $scope.sphone
        };

        loadDate = function () {
            $faAPI.shops.activityList($scope.page).then(function (json) {
                if (json) {
                    $scope.list = json.list;

                    angular.forEach($scope.list, function (o, i) {
                        if (o.activityEndDate) {
                            var ttime = $filter("date")(o.activityEndDateTime, "yyyy/MM/dd HH:mm");
                            if ((new Date(ttime)) > (new Date())) {
                                o.activityOver = false;
                            } else {
                                o.activityOver = true;
                            }
                        }
                    });

                    $scope.page = json.pager;
                }
            });

            if ($faPlatform.weChat) {
                var reqData = {
                    type: '110300',
                    host: $location.host(),
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP',
                    shopId: $scope.sphone
                };

                $faAPI.shops.statis({type: 'statisitics', data: reqData}).then(function (json) {
                });
            }
        }
        loadDate();
    })
    .controller('shopsPreviewAcDetailCtrl', function ($scope, $filter, $stateParams, $state, $timeout, $ionicPopup, $faModal, $faAPI, $faMAP, $faUploader, $faPlatform, $faPopup, $location, $lfShare) {
        $scope.id = $stateParams.id;
        $scope.sphone = $stateParams.sphone;

        $scope.dto = {};
        var shareData = {};

        loadDetail = function () {
            $faAPI.shops.activityDetail({id: $scope.id}).then(function (json) {
                if (json) {
                    $scope.dto = json.dto;

                    shareData = {
                        title: $scope.dto.activityTitle,
                        desc: $scope.dto.activityDesc,
                        link: $location.protocol() + '://' + $location.host() + '/#/shops/previewAcDetail/' + $scope.sphone + '/' + $scope.id + '?share=true&sphone=' + $scope.sphone,
                        imgUrl: 'https://www.superfa.cn/upload/bann/20170117/1484640777250263637.png'
                    };

                    //微信分享
                    $lfShare.wechatShare(shareData);

                    if ($scope.dto.activityEndDate) {
                        var ttime = $filter("date")($scope.dto.activityEndDateTime, "yyyy/MM/dd HH:mm");
                        if ((new Date(ttime)) > (new Date())) {
                            $scope.dto.activityOver = false;
                        } else {
                            $scope.dto.activityOver = true;
                        }
                    }
                }
            });
        }

        if ($scope.id) {
            loadDetail();

            if ($faPlatform.weChat) {
                var reqData = {
                    type: '110301',
                    host: $location.host(),
                    path: $location.path(),
                    param: $location.search(),
                    source: 'WAP',
                    shopId: $scope.sphone,
                    activityId: $scope.id
                };

                $faAPI.shops.statis({type: 'statisitics', data: reqData}).then(function (json) {
                });
            }
        }

        $scope.showPopup = function () {
            $scope.data = {
                activityId: $scope.id
            };

            var myPopup = $ionicPopup.show({
                template: '<input type="text" ng-model="data.userName" placeholder="姓名"><div style="width: 100%;height: 1px;border-bottom: 1px solid #eee;margin: 0 -10px;position: absolute;"></div><input type="text" ng-model="data.userPhone" placeholder="手机" maxlength="11" style="margin-top: 10px;">',
                title: '活动报名',
                scope: $scope,
                buttons: [
                    {text: '取消'},
                    {
                        text: '确定',
                        type: 'bg-red',
                        onTap: function (e) {
                            if (!$scope.data.userName || !$scope.data.userPhone) {
                                e.preventDefault();
                            } else {
                                if (!/^1\d{10}$/.test($scope.data.userPhone)) {
                                    $faPopup.alert({
                                        title: ' 手机号码格式错误'
                                    });
                                    e.preventDefault();
                                    return;
                                }
                                return $scope.data;
                            }
                        }
                    }
                ]
            });

            myPopup.then(function (res) {
                if (res) {
                    $faAPI.shops.activityAddPerson(res).then(function (json) {
                        if (json) {
                            $faPopup.alert({
                                title: '报名成功'
                            });
                        }
                    });
                }
            });
        };
    })
    .controller('subscribeCtrl', function ($scope, $rootScope, $faAPI) {
        $scope.list = [];
        $scope.pager = {
            pageSize: 10,
            pageNo: 1,
            hasNaxtPage: true
        };

        $scope.loadMore = function () {
            $faAPI.shops.clientOrder($scope.pager).then(function (json) {
                $scope.list = $scope.list.concat(json.list);

                $scope.pager.pageNo = json.pager.nextPage;
                $scope.pager.hasNaxtPage = json.pager.hasNaxtPage;

                $scope.$broadcast('scroll.infiniteScrollComplete');

            })
        }
    })
    .controller('clientOrderCtrl', function ($scope, $rootScope, $faAPI, $stateParams, $faPopup, $ionicPopup, $ionicHistory, $faUser, $interval,$faMAP) {

        $scope.sharePhone =$stateParams.sphone;
        var self = $stateParams.self;
        $scope.item = {
            productId: $stateParams.productId,
            productName: $stateParams.productName,
            productType: $stateParams.productType,
            shopperId: $stateParams.sphone,
            reservationAmount: ''
        };
        console.log($scope.item);

        //验证码
        {
            var seCode = {};
            $scope.seCode = seCode;
            seCode.interval = 0;

            //发送验证码
            seCode.sendVcode = function () {
                if (!$scope.item.userPhone) {
                    $faPopup.alert({
                        title: '未填写手机号码'
                    });
                } else if (!/^1\d{10}$/.test($scope.item.userPhone)) {
                    $faPopup.alert({
                        title: ' 手机号码格式错误'
                    });
                } else {
                    $faAPI.shops.shareMakeVcode({mobile: $scope.item.userPhone}).then(function (res) {

                        if(res.statusCode == '0000') {
                            seCode.interval = 60;

                                $interval.cancel(seCode.sendTimer);

                                seCode.sendTimer = $interval(function () {
                                    if (seCode.interval > 0) {
                                        seCode.interval--;
                                    } else {
                                        $interval.cancel(seCode.sendTimer);
                                        seCode.interval = 0;
                                    }
                                }, 1000);
                            }


                    })
                }
            }
        }
        console.log($faUser)
        console.log($faUser.info.mobile)
        $scope.submit = function () {
            if (!$scope.item.userName) {
                $faPopup.alert({
                    title: '请输入姓名'
                });
            } else if (!(/^1[34578]\d{9}$/.test($scope.item.userPhone))) {
                $faPopup.alert({
                    title: '请输入正确手机号'
                });
            } else if( !$scope.item.vCode){
                $faPopup.alert({
                    title: '请输入验证码'
                });
            }else if(!$scope.item.reservationAmount){
                $faPopup.alert({
                    title: '请输入预约金额'
                });
            } else {
               // $faAPI.shops.subClientOrder($scope.item).then(function (json) {


               // })

                if ($stateParams.productType == '01') {//私募
                    $faAPI.order.applyPreTmpSM({
                        oAmount: $scope.item.reservationAmount,
                        oClientName: $scope.item.userName,
                        productId: $scope.item.productId,
                        oRemark: '',
                        validatecode: $scope.item.vCode,
                        shopperId:$stateParams.sphone,
                        mobile:$scope.item.userPhone
                    }).then(function (json) {
                        // $scope.isSuccess = true;
                       $ionicPopup.alert({
                           title: '您已成功预约该产品<br>理财师将会第一时间和您联系',
                           buttons:[
                               {text:'关闭',
                                   type:'button-coltype'}
                           ]
                       }).then(function () {
                           $ionicHistory.goBack();

                       })
                    });
                } else {//自营产品
                    var subForm = {};
                    if(self){
                        //自营产品的参数与平台产品的参数不同
                        subForm.userName = $scope.item.userName;
                        subForm.productName = $scope.item.productName;
                        subForm.reservationAmount = $scope.item.reservationAmount;
                        subForm.productId = $scope.item.productId;
                        subForm.productType = $scope.item.productType;
                        subForm.validatecode = $scope.item.vCode;
                        subForm.shopperId = $stateParams.sphone?$stateParams.sphone:$scope.item.userPhone;
                        subForm.userPhone = $scope.item.userPhone;
                        $faAPI.shops.subClientOrder(subForm).then(function (json) {
                            // $scope.isSuccess = true;
                            $ionicPopup.alert({
                                title: '您已成功预约该产品<br>理财师将会第一时间和您联系',
                                buttons:[
                                    {text:'关闭',
                                    type:'button-coltype'}
                                ]
                            }).then(function () {
                                $ionicHistory.goBack();

                            })
                        });
                    }else {
                        subForm.name = $scope.item.userName;
                        subForm.amount = $scope.item.reservationAmount;
                        subForm.pid = $scope.item.productId;
                        subForm.remark = '';
                        subForm.validatecode = $scope.item.vCode;
                        subForm.shopperId = $stateParams.sphone;
                        subForm.mobile = $scope.item.userPhone;
                        $faAPI.order.applyPre(subForm).then(function (json) {
                            // $scope.isSuccess = true;
                            $ionicPopup.alert({
                                title: '您已成功预约该产品<br>理财师将会第一时间和您联系',
                                buttons:[
                                    {text:'关闭',
                                        type:'button-coltype'}
                                ]

                            }).then(function () {
                                $ionicHistory.goBack();

                            })
                        });
                    }

                }
            }
        }


    })
    .controller('shopChatCtrl', function ($scope, $faUser,$stateParams,$faAPI,$chatToken,$ionicPopup,$timeout,$ionicScrollDelegate,$faMAP,$filter) {

        var shopchat = {}
        $scope.shopchat = shopchat;
        var shareImgUrl = null, shareLink=null, sphone=$stateParams.sphone, proid = $stateParams.proid,
            protype = $stateParams.protype, prosource = $stateParams.prosource;
        $scope.sphone = $stateParams.sphone;

        shopchat.investType = $faMAP.investType;

        shopchat.proid = proid;
        shopchat.protype = protype;
        shopchat.prosource = prosource;

        $scope.isshownewsbar = false;
        if(shopchat.proid && shopchat.protype &&shopchat.prosource) {
            $scope.isshownewsbar = true;
        }

        if(prosource == 'platform') {//非自有产品
            if (protype == '06') {//股权基金
                $faAPI.product.pevcDetail({
                    code: proid
                }).then(function (json) {
                    console.log(json)
                    shareImgUrl = citeImgUrl + json.result.pImageUrl+"?x-oss-process=image/resize,w_200";

                    $scope.item = (function (item) {
                        if (item.expectSaleAmount != 0) {
                            item.process = ((item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2) > 100) ? 100 : (item.allSubscriptionAmount * 100 / item.expectSaleAmount).toFixed(2);
                        } else {
                            item.process = 0;
                        }
                        for (var i = 0; i < item.profitAndRebateList.length; i++) {
                            if (item.profitAndRebateList[i].pIsAgreement == 1) {
                                //是否协议价
                                $scope.isagreement = true;
                            }
                        }
                        return item;
                    })(json.result);

                    //产品详情由富文本拆分的字段
                    try {
                        $scope.summary = JSON.parse(json.result.summary);
                        $scope.pevcDetailData = json;

                    }
                    catch (err) {

                    }

                    shareLink = "http://" + domainname + '/#/product/pevc/' + proid + '?share=true&sharePhone=' + sphone;
                });
            } else if (protype == '01') {//私募
                $faAPI.product.simuDetail({id: proid}).then(function (json) {
                    console.log(json)
                    $scope.item = json;
                    if ($scope.item.detail) {
                        if ($scope.item.detail.lsjzJson) {
                            $scope.item.detail.lsjzJson = angular.fromJson($scope.item.detail.lsjzJson);
                        }
                    }

                    shareImgUrl = 'http://lec.superfa.cn/upload/bann/20160913/1473730864215990394.png?x-oss-process=image/resize,w_200';
                    shareLink = "http://" + domainname + '/#/product/simu/' + proid + '?share=true&sharePhone=' + sphone + '&onlypro=true';
                });
            } else {//其他 02、03、07
                $faAPI.product.detail({code: proid}).then(function (json) {
                    console.log(json)
                    $scope.item = json.result;

                    shareImgUrl = citeImgUrl + json.result.pImageUrl+"?x-oss-process=image/resize,w_200";

                    shareLink = "http://" + domainname + '/#/product/xtzgdetail/' + proid + '?share=true&sharePhone=' + sphone;
                })
            }
        } else {//自有产品
            shareImgUrl = "http://" + domainname +"/img/commimg/logo.png?x-oss-process=image/resize,w_200?x-oss-process=image/resize,w_200";
            $faAPI.product.detailFpShopUserRelProduct({id: proid}).then(function(json){
                console.info(json);
                $scope.item = json.dto;

                shareLink = "http://" + domainname + '/#/myProduct2Detail?id=' + proid + '&share=true&isshare=true&sharePhone=' + sphone;
            });
        }

        //初始化
        var userInfo = {
            appKey: CHAT_APPKEY,
            token: $chatToken.getter()
        };
        console.log($chatToken.getter());
        var targetId = $stateParams.tid;
        $scope.ismaster = $stateParams.ismaster;
        console.log($scope.ismaster);
        $scope.messageList = [];
        var instance;//实例
        $scope.hasmsg;
        var conversationType;
        var mycars = new Array();
        mycars[0] = {
            id:targetId
        } ;
        var d=new Date();
        var mon = d.getMonth() + 1;
        var day = d.getDate();
        var mydate = d.getFullYear() + "-" + (mon<10?"0"+mon:mon) + "-" +(day<10?"0"+day:day);
        $scope.localtime =new Date(mydate+" 23:59:59").getTime();
        $faAPI.shops.rySessionList({
            conversationUsers:angular.toJson(mycars)
        }).then(function(data){
            console.log(data);
            $scope.targetUserInfo = data.userInfos[targetId] || {}

        });
        $scope.oneselfUserImg = $chatToken.getter_img();
        var conversationtype = RongIMLib.ConversationType.PRIVATE; // 私聊
        RongIMLib.RongIMEmoji.init();
        var callbacks = {
            CONNECTED: function (instance) { //传入实例参数
                //获取历史消息
                var conversationType = RongIMLib.ConversationType.PRIVATE;
                //var targetId = 'user15';
                instance.getHistoryMessages(conversationType, targetId, null, 20, {
                    onSuccess: function (list, hasMsg) {
                        console.log('历史消息');
                        console.log(list);
                        console.log(hasMsg);
                        $scope.hasmsg = hasMsg;
                        //渲染会话列表
                        for(var i=0; i<list.length; i++) {//表情
                            list[i].content.content = RongIMLib.RongIMEmoji.symbolToEmoji(list[i].content.content)
                        }

                        //预览页进入此页面默认推送消息
                        if(!proid) {

                            $faAPI.shops.shopUserInfo({
                                loginName: sphone
                            }).then(function (json) {
                                console.info(json)
                                var lcsname = '';
                                if(json.shopperUserInfoDto.userName) {
                                    lcsname = json.shopperUserInfoDto.userName;
                                }
                                var text = "您好!我是理财师"+lcsname+"，有任何理财或产品问题，敬请咨询。\n\n请拨打我的电话："+sphone+"，或直接点击右上角联系我。";

                                var message = {}
                                message.content = {}
                                message.content.content = text;
                                message.content.messageName = "TextMessage";
                                message.conversationType = '2';
                                message.messageType = "TextMessage";
                                message.messageDirection = "2";
                                list.push(message);
                            })
                        }

                        renderHistoryMessages(list, hasMsg, instance);
                    }
                }, null);

                //预览页进入此页面默认推送消息
                //if(!proid) {
                    //console.info("执行发送=========")
                    ////var defaultText = '您好!我是理财师' + $scope.targetUserInfo.nickname + "，有任何理财或生产问题，敬请咨询。\n\n请拨打我的电话：" + $scope.targetUserInfo.userPhone + "或直接点击右上角联系我。";
                    //var defaultText = "您好!我是理财师张三，有任何理财或生产问题，敬请咨询。\n\n请拨打我的电话：17091958691，或直接点击右上角联系我。";
                    //var msg = new RongIMLib.TextMessage({content: defaultText, extra: "附加信息"});
                    //instance.sendMessage(conversationType, targetId, msg, {
                    //        // 发送消息成功
                    //        onSuccess: function (message) {
                    //            console.log('发送消息成功');
                    //            $scope.sendMsgVal = '';
                    //            $scope.messageList.push(message);
                    //            //$scope.$apply();
                    //            console.log($scope.messageList);
                    //            //添加完消息 跳转到最后一条
                    //            $ionicScrollDelegate.$getByHandle('mainScroll').scrollBottom([true]);
                    //        }
                    //    }
                    //);
                //}

            },
            Success: function (id) {
            },
            Received: function (message) {
                //renderHistoryMessages(message);
                if(targetId == message.targetId){
                    message.content.content = RongIMLib.RongIMEmoji.symbolToEmoji(message.content.content);
                    addMessages(message);
                }

            }
        };

        function init(userInfo, callbacks) {
            console.log(userInfo.appKey)
            console.log(userInfo.token)
            if (!userInfo.appKey || !userInfo.token) {
                return false;
            }

            //公有云初始化
            RongIMLib.RongIMClient.init(userInfo.appKey);
            //实例
            instance = RongIMClient.getInstance();
            RongIMLib.RongIMVoice.init();
            console.log('初始化声音库');
            //连接状态监听器
            RongIMClient.setConnectionStatusListener({
                onChanged: function (status) {
                    switch (status) {
                        case RongIMLib.ConnectionStatus.CONNECTED:
                            console.log("链接成功 ");
                            callbacks.CONNECTED && callbacks.CONNECTED(instance);
                            break;
                        case RongIMLib.ConnectionStatus.CONNECTING:
                            console.log('正在链接');
                            break;
                        case RongIMLib.ConnectionStatus.DISCONNECTED:
                            console.log('断开连接');
                            break;
                        case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                            console.log('其他设备登录');
                            break;
                        case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                            console.log('域名不正确');
                            break;
                        case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                            console.log('网络不可用');
                            break;
                    }
                }
            });

            //消息接受监听
            RongIMClient.setOnReceiveMessageListener({
                // 接收到的消息
                onReceived: function (message) {
                    console.log('收到新消息');
                    console.log(message);
                    if(message.messageType == 'TextMessage' || message.messageType == 'VoiceMessage' || message.messageType == 'ImageMessage' ||message.messageType=='RichContentMessage'){
                        console.info("消息监听")
                        callbacks.Received && callbacks.Received(message);
                    }


                }
            });
            //清除当前会话未读数
            clearUnreadCount();

            //开始链接
            RongIMClient.connect(userInfo.token, {
                onSuccess: function (id) {
                    callbacks.Success && callbacks.Success(id);

                },
                onTokenIncorrect: function () {
                    console.log('token无效');
                },
                onError: function (errorCode) {
                    var info = '';
                    switch (errorCode) {
                        case RongIMLib.ErrorCode.TIMEOUT:
                            info = '超时';
                            break;
                        case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                            info = '未知错误';
                            break;
                        case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                            info = '不可接受的协议版本';
                            break;
                        case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                            info = 'appkey不正确';
                            break;
                        case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                            info = '服务器不可用';
                            break;
                    }
                    console.log(info);
                }
            });
        }

        function renderHistoryMessages(list, hasMsg, instance) {
            $scope.messageList = list;
            console.log($scope.messageList);
            $scope.$apply();
            $ionicScrollDelegate.$getByHandle('mainScroll').scrollBottom([true]);
        }
        $scope.getHistoryMessagesMore = function(hasmsg){
            console.log('getHistoryMessagesMore');
            if(hasmsg){
                var conversationType = RongIMLib.ConversationType.PRIVATE;
                instance.getHistoryMessages(conversationType, targetId, null, 20, {
                    onSuccess: function (list, hasMsg) {
                        console.log('历史消息');
                        console.log(list);
                        console.log(hasMsg);
                        $scope.hasmsg = hasMsg;
                        //渲染会话列表
                        $scope.messageList = list.concat($scope.messageList);
                        $scope.$broadcast('scroll.refreshComplete');
                    }
                }, null);
            }

        };
        function addMessages(list) {
            console.log($scope.messageList);
            var messageList =  $scope.messageList;
            messageList.push(list);
            $scope.$apply();
            $ionicScrollDelegate.$getByHandle('mainScroll').scrollBottom([true]);
        }
        $scope.sendMsg = function(){
            var text = $scope.sendMsgVal;
            if (!text) {
                return false;
            }
            var msg = new RongIMLib.TextMessage({content: RongIMLib.RongIMEmoji.emojiToSymbol(text), extra: "附加信息"});
            //var msg = new RongIMLib.TextMessage({content: text, extra: "附加信息"});
            var conversationType = RongIMLib.ConversationType.PRIVATE; // 私聊
            //var targetId = targetId; // 目标 Id
            var that = this;
            instance.sendMessage(conversationType, targetId, msg, {
                    // 发送消息成功
                    onSuccess: function (message) {
                        console.log('发送消息成功');
                        console.log(message)
                        $scope.sendMsgVal = '';
                        console.log(message);
                        message.content.content = RongIMLib.RongIMEmoji.symbolToEmoji(message.content.content)//表情
                        $scope.messageList.push(message);
                        $scope.$apply();
                        console.log($scope.messageList);
                        //添加完消息 跳转到最后一条
                        $ionicScrollDelegate.$getByHandle('mainScroll').scrollBottom([true]);
                    }
                }
            );

        };
        init(userInfo, callbacks);
        function clearUnreadCount(){
            /*
             注意事项：

             此方法清除当前端的未读数，并不会多端同步，多端同步需要发送 SyncReadStatusMessage 	同步给多端 请参考 SendSyncReadStatusMessage。

             */

            var start = Date.now();
            instance.clearUnreadCount(conversationtype,targetId,{
                onSuccess:function(){
                    console.log("清除未读数成功");
                    console.log("清除未读数成功", "success", start);
                },
                onError:function(error){
                    console.log("清除未读数失败");
                    console.log("清除未读数失败", error, start);
                }
            });
             RongIMClient.getInstance().clearMessagesUnreadStatus("conversationType",targetId,{
                        onSuccess:function(isClear){
                            // isClear true 清除成功 ， false 清除失败
                            console.log("清除未读数");
                            console.log(isClear);
                    },
                onError:function(){
                        //清除遇到错误。
                    }
              });
        }
        $scope.playVoice = function(audioFile,duration){
            //预加载 + 播放
            RongIMLib.RongIMVoice.preLoaded(audioFile, function(){
                // 播放声音
                RongIMLib.RongIMVoice.play(audioFile,duration);
            });
        };
        function msgviewimg(){

            $scope.ckShowImg = function(imgurl){
                $scope.showviewimg = true;
                $scope.viewimgurl = imgurl;
            };
            $scope.ckHideImg = function(imgurl){
                $scope.showviewimg = false;
            }
        }
        msgviewimg();
        function onInput(){
            var footer = document.getElementById('footer');

            $scope.inputfocus = function(){
                console.log('inputfocus');
                footer.style.height = '3rem';
            };
            $scope.inputBlur = function(){
                console.log('inputBlur');
                footer.style.height = '1.20625rem';
            }
        }
        onInput();

        $scope.showweixin = function(){
            var data = $scope.targetUserInfo.userWechatNo || '';
            var name = 'weixinbtn';
            function h5Copy(data,name){
                var clipboard = new Clipboard('.'+name, {
                    text: function() {
                        return data;
                    }
                });
                console.log(clipboard);


            }
            h5Copy(data,name);

            var myPopup = $ionicPopup.confirm({
                template: '<h2 style="font-size: 16px" class="weixins text-center">'+data+'</h2>',
                title: '理财师微信号',
                scope: $scope,
                buttons: [
                    {
                        text: '关闭',
                        type: 'button-default',
                        onTap: function(e) {

                        }
                    },
                    {
                        text: '复制',
                        type: 'bg-red',
                        onTap: function (e) {

                            var myPopup = $ionicPopup.show({
                                title: '复制成功',
                                scope: $scope,
                                buttons: []
                            });
                            $timeout(function () {
                                myPopup.close(); //由于某种原因3秒后关闭弹出
                            }, 2000);
                        }
                    }
                ]
            });
            // myPopup.then(function(res){
            //     if(res) {
            //         var myPopup = $ionicPopup.show({
            //             title: '复制成功',
            //             scope: $scope,
            //             buttons: []
            //         });
            //         $timeout(function () {
            //             myPopup.close(); //由于某种原因3秒后关闭弹出
            //         }, 2000);
            //     }
            // });


        }

        //沟通 - 发送产品信息
        //$scope.isShowPro = true;
        $scope.sendProInfo = function(proName){
            var base64Str = '';// 图片转为可以使用 HTML5 的 FileReader 或者 canvas 也可以上传到后台进行转换。
            var imageUri = shareImgUrl; // 上传到自己服务器的 URL。
            console.log(imageUri)
            var title = proName;
            if(prosource == 'platform') {//非自有产品
                if (shopchat.protype != '01') {
                    var qixian = $scope.item.dueTime;

                    if (shopchat.protype == 06) {
                        base64Str = '基准收益：' + $filter('newProfitRender')($scope.item.profitHight.expectAnnualRevenue) +
                            $filter('newProfitFudongRender')($scope.item.profitHight.expectAnnualRevenue)
                            + '\n产品期限：' + qixian + '\n组织形式：' + $filter('zuzhixingshi')($scope.item.peOrganizeShape);
                    } else {
                        base64Str = '预期收益：' + $filter('newProfitRender')($scope.item.profitHight.expectAnnualRevenue) +
                            $filter('newProfitFudongRender')($scope.item.profitHight.expectAnnualRevenue)
                            + '\n产品期限：' + qixian + '\n投资领域：' + shopchat.investType[$scope.item.investType];
                    }
                } else {
                    console.log($scope.item)
                    var zdf = '--', zxjz = '--', jjjlmc='--';
                    if($scope.item.detail.lsjzJson) {
                        zdf = $scope.item.detail.lsjzJson[0].zdf
                    }
                    if($scope.item.detail.lsjzJson) {
                        zxjz = $scope.item.detail.lsjzJson[0].jzdw
                    }
                    if($scope.item.detail.jjjlmc) {
                        jjjlmc = $scope.item.detail.jjjlmc;
                    }

                    base64Str = '涨跌幅：' + zdf +
                        '\n最新净值：' + zxjz + '\n基金经理：' + jjjlmc;
                }
            } else {//自有产品
                var qixian = $scope.item.dueTime;
                base64Str = '预期收益：' + $scope.item.maxRevenue
                    + '\n产品期限：' + qixian + '\n产品分类：' + $scope.item.productType;
            }

            var url = shareLink;
            var msg = new RongIMLib.RichContentMessage({title:title,content:base64Str,imageUri:imageUri,url:url});

            RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
                    onSuccess: function (message) {
                        $scope.isshownewsbar = false;
                        //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                        console.log('发送消息成功');
                        $scope.sendMsgVal = '';
                        console.log(message);
                        $scope.messageList.push(message);
                        $scope.$apply();
                        console.log($scope.messageList);
                        //添加完消息 跳转到最后一条
                        $ionicScrollDelegate.$getByHandle('mainScroll').scrollBottom([true]);
                    },
                    onError: function (errorCode,message) {
                        var info = '';
                        switch (errorCode) {
                            case RongIMLib.ErrorCode.TIMEOUT:
                                info = '超时';
                                break;
                            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                                info = '未知错误';
                                break;
                            case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                                info = '在黑名单中，无法向对方发送消息';
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                                info = '不在讨论组中';
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_GROUP:
                                info = '不在群组中';
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                                info = '不在聊天室中';
                                break;
                            default :
                                info = x;
                                break;
                        }
                        console.log('发送失败:' + info);
                    }
                }
            );
        }
    })
    .controller('shopChatListCtrl', function ($scope, $faAPI,$chatToken) {
        console.log('shopChatListCtrl');
        $scope.chatList;
        var instance;
        var callbacks = {
            CONNECTED: function (instance) { //传入实例参数
                //获取会话列表
                instance.getConversationList({
                    onSuccess: function (conversations) {
                        console.log(conversations);
                        //renderConversationView(conversations, instance);
                        //处理会话列表
                        transConversations(conversations, function (translatedConversations) {
                            //渲染会话列表
                            console.log(translatedConversations);
                            renderConversationView(translatedConversations, instance);
                        })
                    }
                }, null);

            },
            Success: function (id) {
            },
            Received: function (message) {
                instance.getConversationList({
                    onSuccess: function (conversations) {
                        console.log(conversations);
                        //renderConversationView(conversations, instance);
                        //处理会话列表
                        transConversations(conversations, function (translatedConversations) {
                            //渲染会话列表
                            console.log(translatedConversations);
                            renderConversationView(translatedConversations, instance);
                        })
                    }
                }, null);
            }
        };

        function init(userInfo, callbacks) {
            if (!userInfo.appKey || !userInfo.token) {
                return false;
            }

            //公有云初始化
            RongIMLib.RongIMClient.init(userInfo.appKey);
            instance = RongIMClient.getInstance();

            //连接状态监听器
            RongIMClient.setConnectionStatusListener({
                onChanged: function (status) {
                    switch (status) {
                        case RongIMLib.ConnectionStatus.CONNECTED:
                            console.log("链接成功 ");
                            callbacks.CONNECTED && callbacks.CONNECTED(instance);
                            break;
                        case RongIMLib.ConnectionStatus.CONNECTING:
                            console.log('正在链接');
                            break;
                        case RongIMLib.ConnectionStatus.DISCONNECTED:
                            console.log('断开连接');
                            break;
                        case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                            console.log('其他设备登录');
                            break;
                        case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                            console.log('域名不正确');
                            break;
                        case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                            console.log('网络不可用');
                            break;
                    }
                }
            });

            RongIMClient.setOnReceiveMessageListener({
                // 接收到的消息
                onReceived: function (message) {
                    callbacks.Received && callbacks.Received(message);
                }
            });
            //此接口必须在init()方法之后，连接融云服务器 connect 之前调用。
            RongIMClient.getInstance().hasRemoteUnreadMessages(userInfo.token,{
                onSuccess:function(hasMessage){
                    if(hasMessage){
                        // 有未读的消息
                        console.log('是否有未读消息');
                        console.log(hasMessage);

                    }else{
                        // 没有未读的消息
                        console.log('是否有未读消息');
                        console.log(hasMessage);
                    }
                },onError:function(err){
                    // 错误处理...
                    console.log('获取未读消息错误');
                }
            });


            //开始链接
            RongIMClient.connect(userInfo.token, {
                onSuccess: function (id) {
                    callbacks.Success && callbacks.Success(id);
                },
                onTokenIncorrect: function () {
                    console.log('token无效');
                },
                onError: function (errorCode) {
                    var info = '';
                    switch (errorCode) {
                        case RongIMLib.ErrorCode.TIMEOUT:
                            info = '超时';
                            break;
                        case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                            info = '未知错误';
                            break;
                        case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                            info = '不可接受的协议版本';
                            break;
                        case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                            info = 'appkey不正确';
                            break;
                        case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                            info = '服务器不可用';
                            break;
                    }
                    console.log(info);
                }
            });

        }

        function getMockData(url, params, callback) {
            //url 处理 '/user/get_user'
            console.log('getmockdata');
            console.log(params);

            $faAPI.shops.rySessionList({
                conversationUsers:angular.toJson(params)
            }).then(function(data){
                var userInfos = {};

                params.forEach(function (item) {
                    if (item.conversationType === 1) {
                        userInfos[item.id] = data['userInfos'][item.id];
                    } else if (item.conversationType === 3) {
                        userInfos[item.id] = data['groupInfos'][item.id];
                    }
                });
                console.log(userInfos);
                callback(userInfos)
            });
            //$.getJSON('https://rongcloud.github.io/websdk-demo/integrate/conversation-list/conversation-list.json', function (data) {
            //
            //
            //
            //});
        }


        function transConversations(conversations, callback) {

            if (conversations.length) {

                //获取需要查询用户列表
                var conversationUsers = [], userInfos;
                conversations.forEach(function (item) {
                    conversationUsers.push({conversationType: item.conversationType, id: item.targetId});
                });

                //获取用户信息
                getMockData("/user/get_user", conversationUsers, function (data) {
                    userInfos = data;

                    conversations.forEach(function (item) {

                        item["userInfo"] = userInfos[item.targetId];

                    });

                    callback(conversations);
                });


            } else {
                callback(conversations);
            }

        }

        function renderConversationView(translatedConversations, instance) {
            console.log(translatedConversations);
            $scope.chatList = translatedConversations;
            console.log($scope.chatList);
            //$scope.$apply();
            //return new Vue({
            //  el: '#conversationListPage',
            //  data: {
            //    stat: {
            //      currentView: 'conversationList',
            //      currentUserInfo: {
            //        "id": "user1",
            //        "nickname": "产品",
            //        "region": "86",
            //        "phone": "13269772701",
            //        "portraitUri": "http://img.duoziwang.com/2016/12/08/18594927932.jpg"
            //      },
            //      conversationList: translatedConversations
            //    }
            //  },
            //  components: {
            //    conversationList: {
            //      props: ['stat'],
            //      template: '#conversationList',
            //      methods: {
            //        removeConversation: function (conversationType, targetId, index) {
            //          var that = this;
            //          instance.removeConversation(conversationType, targetId, {
            //            onSuccess: function (bool) {
            //              //删除会话成功。
            //              console.log(bool);
            //              //删除本地数据
            //              that.stat.conversationList.splice(index, 1);
            //            },
            //            onError: function (error) {
            //              // error => 删除会话的错误码
            //              console.log(error);
            //            }
            //          });
            //        },
            //
            //        clearConversation: function () {
            //          var conversationTypes = [RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.GROUP];
            //          instance.clearConversations(conversationTypes, {
            //            onSuccess: function (bool) {
            //              // 清除会话成功
            //              console.log(bool);
            //            },
            //            onError: function (error) {
            //              // error => 清除会话错误码。
            //            }
            //          });
            //        }
            //      }
            //    }
            //  }
            //});
        }

        $faAPI.shops.ryToken().then(function(data){
            //初始化
            var userInfo = {
                appKey: CHAT_APPKEY,
                token: data.token
            };
            $chatToken.setter(data.token);
            $chatToken.setter_img(data.portraitUri);
            init(userInfo, callbacks);
        });


        $scope.clearUnreadCount= function(id){
            /*
             注意事项：

             此方法清除当前端的未读数，并不会多端同步，多端同步需要发送 SyncReadStatusMessage 	同步给多端 请参考 SendSyncReadStatusMessage。

             */

            var start = Date.now();
            RongIMClient.getInstance().clearUnreadCount(1,id,{
                onSuccess:function(){
                    console.log("清除未读数成功");
                    console.log("清除未读数成功", "success", start);
                },
                onError:function(error){
                    console.log("清除未读数失败");
                    console.log("清除未读数失败", error, start);
                }
            });
            //RongIMClient.getInstance().clearMessagesUnreadStatus(1,id,{
            //    onSuccess:function(isClear){
            //        // isClear true 清除成功 ， false 清除失败
            //        console.log("清除未读数");
            //        console.log(isClear);
            //    },
            //    onError:function(){
            //        //清除遇到错误。
            //    }
            //});
        };


        $scope.formatdata = function(shijianchuo)
        {
            //shijianchuo是整数，否则要parseInt转换
            function add0(m){return m<10?'0'+m:m }
            var time = new Date(shijianchuo);
            var y = time.getFullYear();
            var m = time.getMonth()+1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
        }
    })
    .controller('shopPerInfoCtrl',function($scope,$state,$stateParams,$rootScope,$faAPI,$faPopup,$faUploader,$ionicHistory,$faPlatform){
        $scope.data = {};
        $scope.updataFile = {};

        $faAPI.shops.detailShopperUserInfo({

        }).then(function(json){
            $scope.data = json.dto
            if(!json.dto.userName) {
                json.dto.userName = $rootScope.shopUserName;
            }
            if($scope.data.companyNameSwith==null||$scope.data.companyNameSwith==''||$scope.data.companyNameSwith==undefined) {
                $scope.data.companyNameSwith = '0'
            }
            if($scope.data.companyPostionSwith==null||$scope.data.companyPostionSwith==''||$scope.data.companyPostionSwith==undefined) {
                $scope.data.companyPostionSwith = '0'
            }
        });
        $scope.cropPhotoCompanyLog = function(){
            //1用户头像/2店铺头像/3店铺背景
            //cropPhoto('sendImage2');
            if($faPlatform.IOSAPP){
                cropPhoto('sendImage2');
            }

            if($faPlatform.androidAPP){

                document.addEventListener("deviceready", OnDeviceReady, false);
                function OnDeviceReady() {
                    cordova.exec(null, null, "MyPlugin", "cropPhoto", ['sendImage2']);
                }

            }
        };

        window.sendImage2 = function(url){
            console.info(url);

            $scope.data.userHeadImg = url;
            $scope.$apply()
        };


        $scope.cropPhotoShopHome = function(){
            //1用户头像/2店铺头像/3店铺背景
            if(!ISWEB){
                if($faPlatform.IOSAPP){
                    cropPhoto('sendImage3');
                }

                if($faPlatform.androidAPP){

                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        cordova.exec(null, null, "MyPlugin", "cropPhoto", ['sendImage3']);
                    }

                }
            }

        };

        window.sendImage3 = function(url){
            console.info(url);

            $scope.data.shopBackground = url;
            $scope.$apply()

            //$faAPI.shops.updateShopperUserInfo({
            //    shopBackground:url,
            //    updateType:3
            //}).then(function(json){
            //    $faPopup.alert({
            //        title:'保存成功'
            //    });
            //});

        };


        $scope.comitdata = function(){
            if(!$scope.data.shopperName){
                $faPopup.alert({
                    title:'请输入分享名称'
                });
                return false
            }
            if(!$scope.data.shopperDesc){
                $faPopup.alert({
                    title:'请输入分享说明'
                });
                return false
            }
            $faAPI.shops.updateShopperUserInfo($scope.data).then(function(json){
                $faPopup.alert({
                    title:'保存成功'
                });

                if ($faPlatform.androidAPP) {

                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        cordova.exec(null, null, "MyPlugin", "shopinfoFinish", []);
                    }

                }
                    $ionicHistory.goBack();
            });
        };
        var t = document.getElementById('up-img-shopperinfo');
        t.addEventListener('change', function(e){
            doUpload(e);
        });
        function doUpload(e){
            var files = e.target.files;
            var fileSize = files[0].size;

            //if (!$faMAP.regular.image.test(files[0].type)) {
            //  $faPopup.alert({
            //    title: '上传的文件格式不对'
            //  });
            //  $element.removeClass('ng-hide');
            //  $element[0].value = '';
            //  return;
            //} else
            if (fileSize > 5242880) {
                $faPopup.alert({
                    title: '上传的文件太大了'
                });
                $element.removeClass('ng-hide');
                $element[0].value = '';
                return;
            } else if (fileSize < 5120) {
                $faPopup.alert({
                    title: '上传的文件太小了'
                });
                $element.removeClass('ng-hide');
                $element[0].value = '';
                return;
            }

            $faUploader.removeAll();
            $faUploader.addFiles(files);
            $scope.files = $faUploader.getFiles();

            $scope.updataFile.isShowLoading = true;
            $scope.updataFile.percent = 0;

            var baseUrl = '';
            if(!$faPlatform.IOSAPP && !$faPlatform.androidAPP){
                baseUrl = fileUploadUrl;
            }else{
                baseUrl = reqUrl + fileUploadUrl;
            }

            $faUploader.startUpload({
                url: baseUrl,
                concurrency: 2,
                onProgress: function(file) {
                    if(file.loaded <= fileSize){
                        $scope.updataFile.percent = ((file.loaded / fileSize) * 100).toFixed(2);
                    }else{
                        $scope.updataFile.percent = 1;
                        $scope.updataFile.isShowLoading = false;
                    }

                    $scope.$apply();
                },
                onCompleted: function(file, res) {
                    var res = angular.fromJson(res);

                    if (res.statusCode === '0000') {
                        var uri = res.attributes.fileUrl;
                        console.log(res);
                        $scope.data.companyLog = uri;
                        console.log($scope.data.companyLog);
                        $scope.isShowUpload = false;
                        $scope.isShowUploadOk = true;
                        //$scope.doUpdate();
                    } else {
                        $faPopup.alert({
                            title: $faMAP.statusCode[res.statusCode]
                        });
                    }

                    $scope.$apply();
                }

            });
        }
    })
    .controller('productEdittCtrl',function($scope,$faAPI,$stateParams,$faPopup){
        //flagTuijian--1 推荐，2-取消推荐
        $scope.data = {
            productType: $stateParams.type,
            productId:$stateParams.id
        };
        $faAPI.shops.shopProductDetail({
            productId:$stateParams.id,
            productType:$stateParams.type
        }).then(function(json){
            $scope.data = json.dto

        });

        $scope.comitdata = function(){
            console.log($scope.data);
            //if(!$scope.data.productPriority){
            //    $faPopup.alert({
            //        title:'请输入正确的优先级'
            //    });
            //    return
            //}
            $scope.data.flagTuijian = 1;
            $faAPI.shops.shopProductTuijian($scope.data).then(function (json) {

                    $faPopup.alert({
                        title:'保存成功'
                    });
                    window.history.back();

            });

        }

    })

    .controller('DimenCodeCtrl',function($scope,$rootScope,$faAPI,$stateParams,$faPopup,$faPlatform){
        try {
            $scope.showMa = "1";
            $scope.showErweima = function (index) {
                $scope.showMa = index;
            }

            var ossran = Math.random();
            $scope.ossran = ossran;

            //$scope.QRcodeUrl = '/wap/api/QRcode/userShopErweima';

            //初始化查询
            {

                $faAPI.shops.userShopErweima({staticbaseUrl: $rootScope.staticBaseUrl, baseUrl: $rootScope.baseUrl, isuseoss:isuseoss}).then(function (res) {
                    $scope.qrcodeHbUrl = res.qrcodeHbUrl;
                    $scope.qrcodeUrl = res.qrcodeUrl;
                })
            }

            //分享二维码
            $scope.shareImg = function () {
                if($faPlatform.androidAPP){
                    var url = "";
                    if($scope.showMa=='1') {
//                        toSharePhoto($scope.qrcodeHbUrl);
                        url = $scope.qrcodeHbUrl+"?x-oss-process=image/resize,w_600&"+ossran;
                    } else {
//                        toSharePhoto($scope.qrcodeUrl);
                        url = $scope.qrcodeUrl+"?x-oss-process=image/resize,w_600&"+ossran;;
                    }
                    document.addEventListener("deviceready", OnDeviceReady, false);
                    function OnDeviceReady() {
                        cordova.exec(null, null, "MyPlugin", "toSharePhoto", [url]);
                    }

                }else{
                    if($scope.showMa=='1') {
                        shopShare($scope.qrcodeHbUrl+"?x-oss-process=image/resize,w_600&"+ossran);
                    } else {
                        shopShare($scope.qrcodeUrl+"?x-oss-process=image/resize,w_600&"+ossran);
                    }
                }
            }

            //保存图片到相册
            $scope.saveImg = function () {
                if($scope.showMa=='1') {
                    saveImageToPhone($scope.qrcodeHbUrl, success, error)
                } else {
                    saveImageToPhone($scope.qrcodeUrl, success, error)
                }
            }

            function saveImageToPhone(url, success, error) {
                var canvas, context, imageDataUrl, imageData;
                var img = new Image();
                try {
                    img.src = url;
                }
                catch(e) {
                    error(e.message);
                }
                img.onload = function() {
                    canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    context = canvas.getContext('2d');
                    context.drawImage(img, 0, 0);
                    try {
                        imageDataUrl = canvas.toDataURL('image/jpeg', 1.0);
                        imageData = imageDataUrl.replace(/data:image\/jpeg;base64,/, '');
                        cordova.exec(
                            success,
                            error,
                            'Canvas2ImagePlugin',
                            'saveImageDataToLibrary',
                            [imageData]
                        );
                    }
                    catch(e) {
                        error(e.message);
                    }
                };
            }

            var success = function(msg){
                $faPopup.alert({
                    title: '保存成功'
                });
            };

            var error = function(err){
                $faPopup.alert({
                    title: '保存失败'
                });
            };

        } catch(e) {
            alert(e)
        }

    })

    //数据统计 交易
    .controller('TransactionCtrl',function($scope,$faAPI,$stateParams,$faPopup, $echartsMap){
        initTrans(-7);

        function initTrans(getTimes) {
            $faAPI.dataStatistics.dataStatistics({getTimes:getTimes}).then(function(data){
                $scope.thisMonth = data ;
                console.log($scope.thisMonth)

                var makeDateArr = [];
                for(var i = 0;i< data.make.length;i++){
                    makeDateArr.push(data.make[i].createDate)
                }
                for(var i = 0;i< data.done.length;i++){
                    makeDateArr.push(data.done[i].createDate);
                }


                Array.prototype.unique2 = function(){
                    this.sort(); //先排序
                    var res = [this[0]];
                    for(var i = 1; i < this.length; i++){
                        if(this[i] !== res[res.length - 1]){
                            res.push(this[i]);
                        }
                    }
                    return res;
                }
                var xAxisArr = [], shopseeArr=[], shopviewArr=[],seriesArr=[];
                xAxisArr = makeDateArr.unique2();//去重后的数组
                console.log(xAxisArr)





                for(var i=0; i<xAxisArr.length; i++) {
                    var isExit = false;
                    for(var j=0; j < data.make.length;j++){
                        if(data.make[j].createDate == xAxisArr[i]) {
                            var curcount = data.make[j].count/10000
                            shopseeArr.push(curcount);
                            isExit = true;
                        }
                    }
                    if(!isExit) {
                        shopseeArr.push(0);
                    }
                }

                for(var i=0; i<xAxisArr.length; i++) {
                    var isExit = false;
                    for(var j=0; j < data.done.length;j++){
                        if(data.done[j].createDate == xAxisArr[i]) {
                            var isCurcount = data.done[j].count/10000
                            shopviewArr.push(isCurcount);
                            isExit = true;
                        }
                    }
                    if(!isExit) {
                        shopviewArr.push(0);
                    }
                }

                if(undefined == xAxisArr[0]){
                    xAxisArr = [0];

                }

                seriesArr=[
                    {
                        name:'预约金额',

                        type:'line',
                        data:shopseeArr
                    },
                    {
                        name:'打款金额',
                        type:'line',
                        data:shopviewArr
                    }
                ]

                console.info(shopseeArr)
                $echartsMap.initQxMap('main', xAxisArr, "单位(万)", ['预约金额', '打款金额'],seriesArr)


            })

        }
        $scope.flowShowTab = -7;
        $scope.MathDay = 7;
        var now = new Date();
        $scope.maxData = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+ now.getDate();


        var date = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
        $scope.minData = date.getFullYear()+"-"+(date.getMonth() + 1)+"-"+date.getDate();



        $scope.flowTab = function(getTimes){
            $scope.flowShowTab = getTimes;
            $scope.MathDay = Math.abs(getTimes);
            initTrans(getTimes)
            var now = new Date();
            $scope.maxData = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+ now.getDate();


            var date = new Date(now.getTime() - $scope.MathDay * 24 * 3600 * 1000);
            $scope.minData = date.getFullYear()+"-"+(date.getMonth() + 1)+"-"+date.getDate();


        }

    })

    //数据统计 流量
    .controller('DataFlowCtrl',function($scope,$faAPI,$stateParams,$faPopup, $echartsMap){
        initDate(-7);

        function initDate(getTimes) {
            $faAPI.dataStatistics.dataFlow({getTimes:getTimes}).then(function(data){
                $scope.thisFlow = data ;
                console.log($scope.thisFlow)

                var xAxisArr = [], shopseeArr=[], shopviewArr=[],seriesArr=[];
                for (var i=data.view.shopSeeCountList.length-1; i>=0; i--) {
                    var d = data.view.shopSeeCountList[i];
                    xAxisArr.push(d.date)

                    shopseeArr.push(d.count)
                }


                if(xAxisArr.length == 0){
                    xAxisArr[0] = 0;
                    shopseeArr[0] = 0;
                }

                console.log(xAxisArr.length)
                for(var i=data.view.shopViewList.length-1; i>=0; i--) {
                    var c = data.view.shopViewList[i]

                    shopviewArr.push(c.count)

                }

                seriesArr=[
                    {
                        name:'浏览量(次)',

                        type:'line',
                        data:shopseeArr
                    },
                    {
                        name:'访问量(人)',
                        type:'line',
                        data:shopviewArr
                    }
                ]

                $echartsMap.initQxMap('flowMain', xAxisArr, "", ['浏览量(次)', '访问量(人)'], seriesArr)

            })
        }

        $scope.MathDay = 7;
        $scope.showTab = -7;


        var now = new Date();
        $scope.maxData = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+ now.getDate();


        var date = new Date(now.getTime() - $scope.MathDay * 24 * 3600 * 1000);
        $scope.minData = date.getFullYear()+"-"+(date.getMonth() + 1)+"-"+date.getDate();



        $scope.getOthData =function (getTimes) {
            $scope.showTab=getTimes;
            $scope.MathDay = Math.abs(getTimes);
            initDate(getTimes);

            var now = new Date();
            $scope.maxData = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+ now.getDate();


            var date = new Date(now.getTime() - $scope.MathDay * 24 * 3600 * 1000);
            $scope.minData = date.getFullYear()+"-"+(date.getMonth() + 1)+"-"+date.getDate();

        }


    })
    //订单汇总--折线图
    .controller('dataSummaryCtrl',function($scope,$state,$faAPI,$stateParams,$faPopup,$faUser,$echartsMap,$ionicSideMenuDelegate,$faModal,$rootScope){
        //initDate(-179);
        $scope.n = 1;
        $scope.name = '金策师';
        function initDate(getTimes) {
            $faAPI.dataStatistics.dataFlow({getTimes:getTimes}).then(function(data){
                $scope.thisFlow = data ;
                console.log($scope.thisFlow)

                var xAxisArr = [], shopseeArr=[], shopviewArr=[],seriesArr=[];
                for (var i=data.view.shopSeeCountList.length-1; i>=0; i--) {
                    var d = data.view.shopSeeCountList[i];
                    xAxisArr.push(d.date)

                    shopseeArr.push(d.count)
                }


                if(xAxisArr.length == 0){
                    xAxisArr[0] = 0;
                    shopseeArr[0] = 0;
                }

                console.log(xAxisArr.length)
                for(var i=data.view.shopViewList.length-1; i>=0; i--) {
                    var c = data.view.shopViewList[i]

                    shopviewArr.push(c.count)

                }

                seriesArr=[
                    {
                        name:'浏览量(次)',

                        type:'line',
                        data:shopseeArr
                    },
                    {
                        name:'访问量(人)',
                        type:'line',
                        data:shopviewArr
                    }
                ]

                $echartsMap.initQxMap('flowMain', xAxisArr, "", ['浏览量(次)', '访问量(人)'], seriesArr)

            })
        }

        $scope.MathDay = 7;
        $scope.showTab = -7;

        //
        //var now = new Date();
        //$scope.maxData = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+ now.getDate();
        //
        //
        //var date = new Date(now.getTime() - $scope.MathDay * 24 * 3600 * 1000);
        //$scope.minData = date.getFullYear()+"-"+(date.getMonth() + 1)+"-"+date.getDate();



        $scope.getOthData =function (getTimes) {
            $scope.showTab=getTimes;
            $scope.MathDay = Math.abs(getTimes);
            initDate(getTimes);

            var now = new Date();
            $scope.maxData = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+ now.getDate();


            var date = new Date(now.getTime() - $scope.MathDay * 24 * 3600 * 1000);
            $scope.minData = date.getFullYear()+"-"+(date.getMonth() + 1)+"-"+date.getDate();

        };
        var _uPhone = $faUser.info.mobile;//取登录人手机号
        //产品查看及分享汇总
        function  newPro(_uPhone,getTimes,pageSize,id) {//浏览
            $faAPI.dataStatistics.dataProduct2({

                uPhone:_uPhone,
                getTimes:getTimes,
                pageSize:pageSize,
                orgid:id


            }).then(function(data){
                $scope.thisData = data;

                if($scope.thisData.map.productCountShare != ''){
                    $scope.isIf = false;
                }else{
                    $scope.isIf = true;
                }

            })
        }


        //折线图及成交订单统计
        function initlinedata(_uPhone,times,id){
            $faAPI.dataStatistics.productCountByTimeAndOrg({//参数:  uPhone 登录人手机号
                uPhone:_uPhone,
                times:times,
                orgid:id
            }).then(function(json){
                console.info('折线图及成交订单统计');
                //返回：make 预约金额折线图数据
                //done 成交订单金额折线图数据
                //makeAll 预约订单总金额
                //doneAll 成交订单总金额
                //donecount 成交订单统计结果<orderNum：订单数量 sumAmount：订单总金额 countType：统计类型>


                var xAxisArr = json.xAxisDatas,//X轴数据
                    _make = json.make,
                    _done = json.done,
                    _makelist=[],//make 预约金额折线图数据
                    _donelist=[],//done 成交订单金额折线图数据
                    seriesArr=[];
                for (var i=0; i< _make.length;  i++) {
                    var d = _make[i];
                    _makelist.push(d.count)
                }

                for(var i1 = 0;i1<_done.length; i1++) {
                    var c = _done[i1];
                    _donelist.push(c.count)

                }

                //if(xAxisArr.length == 0){
                //    xAxisArr[0] = 0;
                //    shopseeArr[0] = 0;
                //}
                seriesArr=[
                    {
                        name:'预约订单',
                        type:'line',
                        data:_makelist
                    },
                    {
                        name:'成交订单',
                        type:'line',
                        data:_donelist
                    }
                ];

                $echartsMap.initQxMap('flowMain', xAxisArr, "", ['预约订单', '成交订单'], seriesArr);

                //预约订单总额
                $scope.makeAll = json.makeAll;
                //成交订单总额
                $scope.doneAll = json.doneAll;
                //成交订单
                $scope.donecount = json.donecount;


            });
        }
        //初始为7天数据
        newPro(_uPhone,-6,100);
        initlinedata(_uPhone,'-6');
        //点击切换时间
        var stime='-6';
        $scope.dataTab = function (n) {
            $scope.n = n;
            console.log();
            if(n==1){
                $scope._times = '-6';
                if($scope.transData.oid){
                    newPro('',$scope._times,100,$scope.transData.oid);
                    initlinedata('',$scope._times,$scope.transData.oid);
                }else {
                    newPro(_uPhone,$scope._times,100);
                    initlinedata(_uPhone,$scope._times);
                }

                $scope.transData.time = $scope._times;
            }else if(n == 2){

                $scope._times = '-29';
                if($scope.transData.oid){
                    newPro('',$scope._times,100,$scope.transData.oid);
                    initlinedata('',$scope._times,$scope.transData.oid);
                }else {
                    newPro(_uPhone,$scope._times,100);
                    initlinedata(_uPhone,$scope._times);
                }

                stime = $scope._times;
                $scope.transData.time = $scope._times;
            }else if(n == 3){

                $scope._times = '-179';
                if($scope.transData.oid){
                    newPro('',$scope._times,100,$scope.transData.oid);
                    initlinedata('',$scope._times,$scope.transData.oid);
                }else {
                    newPro(_uPhone,$scope._times,100);
                    initlinedata(_uPhone,$scope._times);
                }

                $scope.transData.time = $scope._times;
            }else if(n == 4){
                $scope._times = '-365';
                if($scope.transData.oid){
                    newPro('',$scope._times,100,$scope.transData.oid);
                    initlinedata('',$scope._times,$scope.transData.oid);
                }else {
                    newPro(_uPhone,$scope._times,100);
                    initlinedata(_uPhone,$scope._times);
                }

                $scope.transData.time = $scope._times;
            }else {
                $scope._times = '-1';
                if($scope.transData.oid){
                    newPro('',$scope._times,100,$scope.transData.oid);
                    initlinedata('',$scope._times,$scope.transData.oid);
                }else {
                    newPro(_uPhone,$scope._times,100);
                    initlinedata(_uPhone,$scope._times);
                }

                $scope.transData.time = $scope._times;
            }
            stime = $scope._times
        };

        //跳转产品查看详情
        $scope.goDataProductlist = function(param,type,productName,num){
            console.log(param,type);
            if(num>0){
                $state.go('dataProductlist',{param:param,type:type,productName:productName,id:$scope.id,name:$scope.name,tabTime:stime})
            }

        };

        //跳转产品分享详情
        $scope.dataMechHome = function(productName,param,num){
            console.log(productName);
            if(num>0){
                $state.go('dataMechHome',{productName:productName,param:param,id:$scope.id,name:$scope.name,tabTime:stime})
            }

        };


        //跳转订单详情
        $scope.goTransaction = function(amountType,num){
            //金额为0，不跳转详情--阿杜
            if(num>0){
                $state.go('dataOrderDetails',{amountType:amountType,id:$scope.id,name:$scope.name,tabTime:stime})
            }

        };


        $scope.transData = {
            phone:_uPhone,
            time:'',
            oid:''
        };//横屏折线图条件
        //机构树形菜单
        function initTheTree(){
            $faAPI.dataStatistics.getOrgTreeByPhone({//参数:  uPhone 登录人手机号
                uPhone:_uPhone
            }).then(function(json){
                console.log('机构树形菜单');
                console.log(json);
                $(document).ready(function(){
                    var _list  = json.list;

                        try {
                            $scope.atName = _list[0].name;
                            _list[0].open = true;//打开第一层节点
                            $.fn.zTree.init($("#treeDemo"), setting,_list);
                            sleNode($scope.id);
                        }catch(e){
                            console.log(e);
                        }



                });

            });
            var setting = {
                data: {
                    simpleData: {
                        enable: true
                    },
                    treeNode:{
                        open:true
                    }
                },
                view: {
                    //showIcon: false,
                    showLine: false
                },
                callback:{ //回调函数
                    /**
                     * event:鼠标事件
                     * treeId：树的容器id
                     * treeNode：当前点击的节点
                     */
                    beforeClick:function(treeId,treeNode,clickFlag){
                        console.log(treeNode);
                        $scope.id = treeNode.id;
                        $scope.name = treeNode.name;
                        $scope.clickshuBtn =  treeNode.currentLogin;
                        //getData(treeNode.id);
                        //折线图及成交订单统计
                        //选择根节点的时候传手机号
                        if(treeNode.level == 0){
                            initlinedata(_uPhone,$scope._times);
                            //产品查看及分享汇总
                            newPro(_uPhone,$scope._times,100);
                            $scope.transData.oid = '';
                        }else {
                            initlinedata('',$scope._times,treeNode.id);
                            //产品查看及分享汇总
                            newPro('',$scope._times,100,treeNode.id);
                            $scope.transData.oid = treeNode.id;
                        }
                        //$ionicSideMenuDelegate.toggleRight();
                        $scope.summModal.hide();
                    }
                }
            };
        }

        //选中指定节点
        function sleNode(pid){
            console.log(pid);
            var  zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
            var node = zTree_Menu.getNodeByParam("id",pid);
            //var nodes = zTree_Menu.getNodes();
            //if (nodes.length>0) {
            //    zTree_Menu.selectNode(nodes[4]);
            //}
            zTree_Menu.selectNode(node);//指定选中ID的节点
            //zTree_Menu.expandNode(node, true, true);//指定选中ID节点展开

        }
        //打开右侧菜单
        $scope.toggleRightSideMenu = function(){
            //$ionicSideMenuDelegate.toggleRight();
            $faModal('summModal', 'views/data/summaryModal.html', $scope, {
                initialize: function () {
                    initTheTree();

                }
            });
            $scope.modal.summModal();
        };
        //关闭右侧菜单
        $scope.closesmummary = function(){
            console.log('closesmummary');
            $scope.summModal.hide();
        };

        //打开横屏
        $scope.openTransverse = function(){
            screen.orientation.lock('landscape');
            if($scope.transData.oid){
                $state.go('transverse',{time:$scope.transData.time,oid:$scope.transData.oid});
            }else {
                $state.go('transverse',{phone:$scope.transData.phone,time:$scope.transData.time});
            }

        }
    })
    //横屏展示折线图
    .controller('transverseCtrl',function($stateParams,$scope,$state,$faAPI,$echartsMap,$timeout){
         console.log('transverseCtrl');
         $scope.n = 1;
         var _phone = $stateParams.phone;
         var _time = $stateParams.time;
         var _oid = $stateParams.oid;


        $scope.dataTab = function (n) {
            $scope.n = n;
            if(n==1){
                $scope._times = '-6';
                initlinedata(_phone,$scope._times,_oid);
            }else if(n == 2){
                $scope._times = '-29';
                initlinedata(_phone,$scope._times,_oid);
            }else if(n == 3){
                $scope._times = '-179';
                initlinedata(_phone,$scope._times,_oid);
            }else if(n == 4){
                $scope._times = '-365';
                initlinedata(_phone,$scope._times,_oid);
            }else {
                $scope._times = '-1';
                initlinedata(_phone,$scope._times,_oid);
            }

        };

        //折线图及成交订单统计
        function initlinedata(_uPhone,times,id){
            $faAPI.dataStatistics.productCountByTimeAndOrg({//参数:  uPhone 登录人手机号
                uPhone:_uPhone,
                times:times,
                orgid:id
            }).then(function(json){
                console.info('折线图及成交订单统计');
                //返回：make 预约金额折线图数据
                //done 成交订单金额折线图数据
                //makeAll 预约订单总金额
                //doneAll 成交订单总金额
                //donecount 成交订单统计结果<orderNum：订单数量 sumAmount：订单总金额 countType：统计类型>


                var xAxisArr = json.xAxisDatas,//X轴数据
                    _make = json.make,
                    _done = json.done,
                    _makelist=[],//make 预约金额折线图数据
                    _donelist=[],//done 成交订单金额折线图数据
                    seriesArr=[];
                for (var i=0; i< _make.length;  i++) {
                    var d = _make[i];
                    _makelist.push(d.count)
                }

                for(var i1 = 0;i1<_done.length; i1++) {
                    var c = _done[i1];
                    _donelist.push(c.count)

                }

                //if(xAxisArr.length == 0){
                //    xAxisArr[0] = 0;
                //    shopseeArr[0] = 0;
                //}
                seriesArr=[
                    {
                        name:'预约订单',
                        type:'line',
                        data:_makelist
                    },
                    {
                        name:'成交订单',
                        type:'line',
                        data:_donelist
                    }
                ];

                $echartsMap.initQxMap('flowMain_tansverse', xAxisArr, "", ['预约订单', '成交订单'], seriesArr);

                //预约订单总额
                $scope.makeAll = json.makeAll;
                //成交订单总额
                $scope.doneAll = json.doneAll;
                //成交订单
                $scope.donecount = json.donecount;


            });
        }

        $scope.goSummary = function(){
            //退出关闭横屏
            screen.orientation.lock('portrait');
            $state.go('dataSummary');
        }

        var worldMapContainer = document.getElementById('flowMain_tansverse');

//用于使chart自适应高度和宽度,通过窗体高宽计算容器高宽
        var resizeWorldMapContainer = function () {
            worldMapContainer.style.width = window.innerWidth+'px';
            worldMapContainer.style.height = window.innerHeight-48-50-66+'px';
        };
        $timeout(function(){
            resizeWorldMapContainer();
            initlinedata(_phone,_time,_oid);
        },100);

    })
    //数据统计 产品
    .controller('DataProductCtr',function($scope,$faAPI,$stateParams,$faPopup, $echartsMap){
        $scope.txt = '暂无数据';
        $scope.isIf = false;
        newPro(-7,500);

        function  newPro(getTimes,pageSize) {//浏览
            $faAPI.dataStatistics.dataProduct({getTimes:getTimes,pageSize:pageSize}).then(function(data){
                $scope.thisData = data;
                
                console.log($scope.thisData)
               if($scope.thisData.map.ProductCountSee != ''){
                    $scope.isIf = false;
               }else{
                   $scope.isIf = true;
               }

            })
        }

        function  proYuyue(getTimes,pageSize) {//预约
            $faAPI.dataStatistics.dataProduct({getTimes:getTimes,pageSize:pageSize}).then(function(data){
                $scope.thisData = data;
                console.log($scope.thisData.make)

                if($scope.thisData.make != ''){
                    $scope.isIf = false;
                }else{
                    $scope.isIf = true;
                }

            })
        }

        function  proPay(getTimes,pageSize) {//打款
            $faAPI.dataStatistics.dataProduct({getTimes:getTimes,pageSize:pageSize}).then(function(data){
                $scope.thisData = data;
                console.log($scope.thisData.done)
                if($scope.thisData.done != ''){
                    $scope.isIf = false;
                }else{
                    $scope.isIf = true;
                }

            })
        }

        $scope.headTab = '1';
        $scope.showHeadTab = function (index) {//头部Tab：浏览、预约、打款
            $scope.headTab = index;
        }
        $scope.countBy = -7;
        $scope.showCountBy = function (index) {//二级Tab：7天、1个月、半年、一年
            $scope.countBy = index;

            if($scope.headTab =='1') {
                newPro(index, 500);
            } else if($scope.headTab =='2') {
                proYuyue(index, 500);
            } else {
                proPay(index, 500);
            }
        }

        //头部浏览、预约、打款切换
        $scope.$watch('headTab', function (newVal, oldVal, scope) {
            if(newVal !=oldVal) {
                $scope.countBy = -7;
                if($scope.headTab == 1){
                    newPro(-7, 500);
                }else if($scope.headTab == 2){
                    proYuyue(-7, 500);
                }else{
                    proPay(-7, 500);
                }

            }
        },true)


    })

    .controller('FastLoginCtrl',function($scope,$rootScope,$faAPI,$faUser,$faUtil,$stateParams,$faPopup,$interval){
        var backurl = $stateParams.backurl;
        var pathToken = $stateParams.pathToken;

        console.info(backurl)

        var fastLogin = {}
        $scope.fastLogin = fastLogin;

        fastLogin.interval = 0;
        fastLogin.data = {
            _pt: 'wap',
            loginName: $faUser.info.mobile,
            validatecode: ''
        };

        fastLogin.sendVcode = function () {
            var _data = this.data;
            if (!fastLogin.data.loginName) {
                $faPopup.alert({
                    title: '未填写手机号码'
                });
            } else if (!/^1\d{10}$/.test(fastLogin.data.loginName)) {
                $faPopup.alert({
                    title: ' 手机号码格式错误'
                });
            } else {
                fastLogin.interval = 90;
                $faAPI.media.sendLoginVcode({mobile: fastLogin.data.loginName}).then(function (resq) {
                    if(resq.AB) {
                        $faPopup.alert({
                            title: '短信请求过于频繁，请稍候再试！'
                        });
                    } else {
                        $interval.cancel(fastLogin.sendTimer);

                        fastLogin.sendTimer = $interval(function () {
                            if (fastLogin.interval > 0) {
                                fastLogin.interval--;
                            } else {
                                $interval.cancel(fastLogin.sendTimer);
                                fastLogin.interval = 0;
                            }
                        }, 1000);
                    }
                });
            }
        }

        //fastLogin.update = function (json) {
        //    $faUser.update();
        //    $faUtil.cookie('_token') && $faUtil.localStorage('_token', $faUtil.cookie('_token').replace(/\"/g, ''));
        //}

        fastLogin.done = function () {
            if(backurl.indexOf('rankIndex') > -1) {
                fastLogin.data.pathToken = "activityRole";
            }

            if (!fastLogin.data.loginName) {
                $faPopup.alert({
                    title: '请输入手机号码'
                });
            } else if (!/^1\d{10}$/.test(fastLogin.data.loginName)) {
                $faPopup.alert({
                    title: '手机号码格式错误'
                });
            } else if (!fastLogin.data.validatecode) {
                $faPopup.alert({
                    title: '请输入手机验证码'
                });
            } else {
                $faAPI.user.quickLogin(fastLogin.data).then(function (json) {

                    $faPopup.alert({
                        title: '签到成功!'
                    });
                    window.localStorage.setItem("rankPhone", fastLogin.data.loginName);
                    window.location.href= decodeURI(backurl)

                });
            }
        }
    })
    .controller('promptCtrl',function($scope,$rootScope,$faAPI,$faUser,$faUtil,$stateParams,$faPopup,$interval){

    })

//帮助与反馈
    .controller('HelpLink',function($scope,$rootScope,$faAPI,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$faPlatform){
        // var autoTextarea = function(elem, extra, maxHeight) {
        //     extra = extra || 0;
        //     var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
        //         isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
        //         addEvent = function(type, callback) {
        //             elem.addEventListener ?
        //                 elem.addEventListener(type, callback, false) :
        //                 elem.attachEvent('on' + type, callback);
        //         },
        //         getStyle = elem.currentStyle ? function(name) {
        //             var val = elem.currentStyle[name];
        //             if (name === 'height' && val.search(/px/i) !== 1) {
        //                 var rect = elem.getBoundingClientRect();
        //                 return rect.bottom - rect.top -
        //                     parseFloat(getStyle('paddingTop')) -
        //                     parseFloat(getStyle('paddingBottom')) + 'px';
        //             };
        //             return val;
        //         } : function(name) {
        //             return getComputedStyle(elem, null)[name];
        //         },
        //         minHeight = parseFloat(getStyle('height'));
        //     elem.style.resize = 'none';
        //     var change = function() {
        //         var scrollTop, height,
        //             padding = 10,
        //             style = elem.style;
        //         if (elem._length === elem.value.length) return;
        //         elem._length = elem.value.length;
        //         if (!isFirefox && !isOpera) {
        //             padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
        //         };
        //         scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        //         elem.style.height = minHeight + 'px';
        //         if (elem.scrollHeight > minHeight) {
        //             if (maxHeight && elem.scrollHeight > maxHeight) {
        //                 height = maxHeight - padding;
        //                 style.overflowY = 'auto';
        //             } else {
        //                 height = elem.scrollHeight - padding;
        //                 style.overflowY = 'auto';
        //             };
        //             style.height = height + extra + 'px';
        //             scrollTop += parseInt(style.height) - elem.currHeight;
        //             document.body.scrollTop = scrollTop;
        //             document.documentElement.scrollTop = scrollTop;
        //             elem.currHeight = parseInt(style.height);
        //         };
        //     };
        //     addEvent('propertychange', change);
        //     addEvent('input', change);
        //     addEvent('focus', change);
        //     change();
        // };
        //
        // var text = document.getElementById("help_textarea");
        // autoTextarea(text);




        //请求历史消息队列

        var feedback = {}
        $scope.feedback= feedback;

        ////用户反馈查询接口
        function initData(userphone) {
            var subForm = {}
            subForm.fpUserPhone = userphone;
            $faAPI.shops.queryFpFaUserFeedback(subForm).then(function (json) {
                $scope.temp = json.list;
                console.log($scope.temp)

                //var item = {};
                //item.id = 'RGZN';
                //$scope.temp.push(item);

                $ionicScrollDelegate.$getByHandle('mainScroll').scrollBottom()
            })
        }
        initData($faUser.info.mobile);

      //反馈 点击发送消息函数
        feedback.content = ''
        $scope.addNewes = function(){
            var subForm = {}
            subForm.content = feedback.content;
            subForm.fpUserId = $faUser.info.id;
            subForm.fpUserPhone = $faUser.info.mobile;
            subForm.type = 0;
            //用户反馈新增接口
            $faAPI.shops.addFpFaUserFeedback(subForm).then(function(json){
                ////用户反馈查询接口
                console.log(json)

                //initData($faUser.info.mobile)
                $scope.temp.push(subForm);
                $ionicScrollDelegate.$getByHandle('mainScroll').scrollBottom()

                feedback.content = ''
            })

        }

        $scope.keyboardheight = 0;
        $scope.textareaFocus = function() {
            if($faPlatform.IOSAPP) {
                window.addEventListener('native.keyboardshow', function keyboardShowHandler(e) {
                    //e.keyboardHeight 这个可以直接获取软键盘的高度
                    $scope.keyboardheight = e.keyboardHeight;
                    $scope.$apply();
                });
            }
        }

        $scope.textareaBlur = function() {
            $scope.keyboardheight = 0;
        }


    })

    .controller('bootCtrl',function($scope,$rootScope,$faAPI,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate){
        var initIndex = $stateParams.initIndex;
        $scope.initIndex = initIndex;
        if(!initIndex) {
            initIndex = 0;
        } else {
            setTimeout(function(){
                $ionicSlideBoxDelegate.slide(initIndex)
            }, 0)
        }
    })

//店招控制器
    .controller('shopPicturesCtr',function($scope,$rootScope,$faAPI,$faModal,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate,$faPlatform){
        $scope.baseUrl = reqUrl;

        var userbackimgs = [];
        $faAPI.shops.fpShopBackground().then(function(data){
            console.log(data)
            $scope.news = data.news;  //热点-实事
            $scope.langs = data.langs; //专业-卓越
            $scope.userBack = data.userBack; //个人定制

            userbackimgs = angular.copy(data.userBack);

            if($scope.userBack[0].backgroudImg != ""&&$scope.userBack[1].backgroudImg == "") {
                $scope.userBack[1].backgroudImg = "/img/commimg/shopPro_beijing.jpg";
            }
        })

        var imgurl = null;
        $faModal('shop_prev','views/modals/shopPrevdetail.html',$scope, {
            initialize: function () {
                $scope.backImgUrl = imgurl;
            }
        });

        $scope.toYualan = function(url) {
            imgurl = url;
            $scope.modal.shop_prev();
        }

        $scope.sendImage3 = function (url) {
           /* $scope.shopperUserInfoDto.shopBackground = url;*/
            console.info(url)
            if($scope.userBack[0].backgroudImg == url) {
                $faPopup.alert({
                    title: '已设置为当前店招背景'
                });
                return false;
            }

            $faAPI.shops.updateShopperUserInfo({
                shopBackground: url,
                updateType: 3
            }).then(function (json) {
                $faPopup.alert({
                    title: '保存成功'
                });

                if (userbackimgs[0].backgroudImg == "" && userbackimgs[1].backgroudImg == ""){
                    console.info("执行")
                    $scope.userBack[0].backgroudImg = url;
                    $scope.userBack[1].backgroudImg = "/img/commimg/shopPro_beijing.jpg"

                    userbackimgs[0].backgroudImg = url;
                    userbackimgs[1].backgroudImg = "/img/commimg/shopPro_beijing.jpg";
                }else{
                    $scope.userBack[1].backgroudImg =$scope.userBack[0].backgroudImg;
                    $scope.userBack[0].backgroudImg = url;
                }
               // $scope.$apply()
            });
        };


        //调用原生上传店铺背景图片
        $scope.cropPhotoShopHome = function($index,url){
            if($index == 0) {
                //1用户头像/2店铺头像/3店铺背景
                if (!ISWEB) {
                    if ($faPlatform.IOSAPP) {
                        cropPhoto('sendImage3');
                    }

                    if ($faPlatform.androidAPP) {

                        document.addEventListener("deviceready", OnDeviceReady, false);
                        function OnDeviceReady() {
                            cordova.exec(null, null, "MyPlugin", "cropPhoto", ['sendImage3']);
                        }

                    }
                }
            } else {
                imgurl = url;
                $scope.modal.shop_prev();
            }

        };

        window.sendImage3 = function(url){
            console.info(url);

            $scope.userBack[1].backgroudImg = $scope.userBack[0].backgroudImg;
            $scope.userBack[0].backgroudImg = url;
            $scope.$apply()

            $faAPI.shops.updateShopperUserInfo({
                shopBackground:url,
                updateType:3
            }).then(function(json){
                $faPopup.alert({
                    title:'保存成功'
                });

            });

        };

    })

    //金策师资讯
    .controller('InformationCtr',function($scope,$state,$rootScope,$faAPI, $authorize,$ionicPopup,$faModal,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate,$faPlatform,$sce,$location, $controller){
        $scope.baseUrl = reqUrl;
        var sphone = $stateParams.sphone;
        $scope.sharephone = sphone;
        console.log($faUser)
        if(sphone) {
            $scope.phone = sphone;
        } else {
            $scope.phone = $faUser.info.mobile;
        }

       //用户信息接口
        function init(){
            $faAPI.shops.shopUserInfo({loginName: $scope.phone}).then(function(data){
                $scope.item = data.shopperUserInfoDto;
                $scope.shopperUserInfoDto = data.shopperUserInfoDto;
                $scope.user = data.dto;
                $scope.prodata = data.pro;   //关联产品
                //微信授权
                if ($faPlatform.weChat) {
                    if ($stateParams.sphone) {
                        //是否微信授权
                        if (!data.wechatId) {
                            $authorize.maAuth();
                        }
                    }
                }
            })
        }

        //大盘指数数据
        $faAPI.shops.listCompositeIndexLog({indexType :1}).then(function(data){
            $scope.list = data.list;
            $scope.listData = [];
            for(var i = 0;i<$scope.list.length;i++){
                if($scope.list[i].indexName != '恒生指数'){
                    $scope.listData.push($scope.list[i])
                }
            }
            console.log($scope.list)
        })

        //资讯首页查询接口
        function query() {
            $faAPI.shops.queryInformation({userId: $scope.phone}).then(function (json) {
                console.log(json)
                $scope.newflash = json.immediateList;  //即时快讯
                $scope.newBirefList = json.birefList;   //资讯简介
                $scope.newhotList = json.hotList;       //热点资讯
                $scope.newmoringList = json.moringList;   //早鸟驿站
                //if(json.pro){
                //    $scope.prodata = json.pro[0] || [];   //关联产品
                //}


                //消息轮播滚动
                setTimeout(function(){
                        $interval.cancel($rootScope.timer);
                    var nums = $('.hezi').children('.hezi_gun')
                    $scope.nums = nums;
                    $rootScope.timer = $interval(function () {
                        $('.swp-con').find('.hezi').animate({
                            marginTop: '-60px'
                        }, 1000, function () {
                            $(this).css({marginTop: "0px"});
                            var li = $(".hezi").children().first().clone()
                            $(".hezi div:last").after(li);
                            $(".hezi div:first").remove();

                        })
                    }, 2000)
                },600)

            })
        }
        query();

        //点赞统计
        $scope.dianzan =function(d) {
            $faAPI.shops.addFpShopInformationDz({userId: $scope.phone,informationId:d.id}).then(function (jsondata) {
                d.dzFlag = jsondata.item.dzFlag;
                d.dzNum = jsondata.item.dzNum;
            })
        }

        /*早鸟驿站签到*/
        var qiandao;
        var mask = document.getElementById('maskId');
        var floatwrap = document.getElementById('floatwrapId');

        var testmap = function(){
            $faAPI.shops.queryTopTen({userPhone: $scope.phone}).then(function(data){
                console.log(data);
                $scope.listimg = data.topTens;
                $scope.listLength = $scope.listimg.length;
                console.log($scope.listLength)
                qiandao = data.signIn;
                $scope.qiantrue = qiandao;
            })
        }

        $scope.$watch('phone', function (newVal, oldVal, scope) {
            if($scope.phone) {
                init();
                testmap();
            }
        });

        //隐藏弹窗方法
        $scope.ishide = function(){
            mask.style.display = "none";
            floatwrap.style.display = "none";
        }
        //弹出弹窗方法
        $scope.isShow = function(){
            mask.style.display = "block";
            floatwrap.style.display = "block";
        }

        $scope.qianTxtcli = function(){
            if(qiandao == true){
                //已签到
                console.log("已经签到");
                $faAPI.shops.querySort().then(function(data){
                    console.log(data)
                    $scope.floatlist = data;
                    //弹出弹窗
                    $scope.isShow();
                })
            }else{
                //未签到
                $faAPI.shops.addFpShopSignin().then(function(data){
                    console.log('未签到');
                    $faAPI.shops.querySort().then(function(data){
                        console.log(data)
                        $scope.floatlist = data;
                        //弹出弹窗
                        $scope.isShow();
                        testmap();
                    })
                })
            }
        }

        //详情
        $scope.listDetail = function(d,num){
            if(num==2) {//热点咨询
                if($scope.sharephone) {
                    $state.go('redianDetail', {id: d.id, type: false, sphone:$scope.sharephone});
                } else {
                    $state.go('redianDetail', {id: d.id, type: ''});
                }
                setTimeout(function(){
                    d.browseNum ++;
                }, 1000)
            } else {//咨询简报
                if(!$scope.sharephone){
                    if (!ISWEB) {
                        if ($faPlatform.IOSAPP) {
                            Briefing('资讯简报', d.articleLink, d.birefDesc, d.hotImg)
                        }else if ($faPlatform.androidAPP) {
                            document.addEventListener("deviceready", OnDeviceReady, false);
                            function OnDeviceReady() {
                                cordova.exec(null, null, "MyPlugin", "jianbao", ['资讯简报',d.birefDesc,d.hotImg,d.articleLink]);
                            }
                        }
                    }
                }else{
                    window.location.href = d.articleLink;
                }
            }
        }
        $scope.toView = function (type, id) {

            if (type && id) {
                var url = '';

                if (type == '01') {
                    url = 'product.simu';

                } else if (type == '02' || type == '03') {
                    url = 'product.xtzgdetail';
                } else if (type == '07') {
                    url = 'product.xtzgdetail';

                }
                else if (type == '06') {
                    url = 'product.pevc';

                }

                $state.go(url, {id: id});
            } else {
                console.log('error,,');
            }

        };
        //分享
        $scope.fxInformation = function(name,desc,img_url, flag,id){
            var linkurl;
            var type = true;
            if(!desc){
                desc = '精选金融快讯，财经简报，热点资讯专业点评，尽在金策师';
            }
            if(flag == 0) {
                linkurl = reqUrl + '/#/shops/information?sphone=' + $scope.phone
            } else if(flag == 3) {
                linkurl = reqUrl + '/#/infromationHotspotDetail/'+ id + '/' + type + '?sphone='+ $scope.phone
            }else if(flag == 4){
                linkurl = reqUrl + '/#/infromationEarlyBirdDetail/'+ id + '/' + type + '?sphone='+ $scope.phone
            }
             if(img_url){
                    if(img_url.indexOf("http")>-1){
                        img_url=img_url
                    }else{
                        img_url = reqUrl+ img_url+'?x-oss-process=image/resize,m_fill,h_100,w_100';
                     }
             }else {
                img_url = 'http://lec.superfa.cn/upload/bann/20161208/1481164249317854085.png';
             }
             var shareData = {
                 title: name,
                 desc: desc,
                 link: linkurl,
                 /*link: $location.protocol() + '://' + $location.host() + '/#/shops/information?sphone=' + $scope.phone,*/
                 imgUrl: img_url
             };
            console.log(name,desc,img_url,shareData.link)
            if($faPlatform.androidAPP){
                document.addEventListener("deviceready",OnDeviceReady, false);

                function OnDeviceReady()
                {
                    cordova.exec(null, null, "MyPlugin", "toActivityShare", [shareData.title,shareData.desc,shareData.link,shareData.imgUrl]);
                }
                //window.shareCallBack();
            }else{
                actionShare(shareData.title,shareData.desc,shareData.link,shareData.imgUrl);
            }
        }

      /*  $faModal('shopperInfo', 'views/modals/shopperInforWin.html', $scope, {
            initialize: function () {
                setTimeout(function(){
                    $controller('shopPerInfoCtrl', {$scope: $scope})
                },200)
            }
        });
        $scope.toShopperInfo = function() {
            $scope.modal.shopperInfo();
        }*/

        $scope.$on("$ionicView.enter", function () {
            //页面启动缓存时,其controller中不会反复执行，但会执行此监听-
                init()
        });
        //删除关联
        $scope.delmsgpro = function(id){
            $faAPI.shops.deleteFpShopProjectInformationL({
                id:id
            }).then(function(redata){
                init()
            });
        }

    })
    /*及时快讯*/
    .controller('newFlashListCtr',function($scope,$state,$rootScope,$faAPI, $ionicPopup,$faModal,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate,$faPlatform){
        $scope.baseUrl = reqUrl;
        var sphone = $stateParams.sphone;
        $scope.sharephone = sphone;
        var type = $stateParams.type;
        console.log(type)
        if(sphone) {
            $scope.phone =sphone;
        } else {
            $scope.phone = $faUser.info.mobile;
        }
        $faAPI.shops.shopUserInfo({loginName: $scope.phone}).then(function(data){
            $scope.item = data.shopperUserInfoDto;
            $scope.user = data.dto;
        })
        function query(){
            $faAPI.shops.queryInformation({userId: $scope.phone}).then(function(json){
                console.log(json)
                $scope.newflash = json.immediateList;  //即时快讯
                console.log($scope.newflash)

                var s =  $scope.newflash[0].releaseTime;
                startTime = s.replace(/\-/g, "/");
                //取当前年月日
                var data = new Date(startTime);
                $scope.currentTime = data.getFullYear()+'年'+(data.getMonth()+1)+'月'+data.getDate()+'日';

            })
        }
        query();

        //点赞统计
        $scope.dianzan =function(d) {
            console.log($scope.phone)
            $faAPI.shops.addFpShopInformationDz({userId: $scope.phone,informationId:d.id}).then(function (jsondata) {
                d.dzFlag = jsondata.item.dzFlag;
                d.dzNum = jsondata.item.dzNum;
            })
        }

        $faModal('shop_listDetail','views/modals/newListDetail.html',$scope, {
            initialize: function () {
                $scope.isWindow = true;
            },
            toShopHome: function(sphone){
                goHome(sphone)
                this.hide();
            }
        });

        $scope.toShopHome =  function(sphone){
            goHome(sphone)
        }
        var goHome = function(sphone) {
            if(!type){
                $state.go('shopPreview', {sphone:sphone, isFromZixun:true})
            }else{
                $state.go('shopPreview', {sphone:sphone, isFromZixun:true})
            }

        }



        function test(data) {
            var str =JSON.stringify(data);
            var reg = new RegExp("&tp=webp","g");
            var a = str.replace(reg,"");
            var detail = $.parseJSON(a);
            return detail;
        }

        //即时快讯详情接口
        $scope.listDetail = function(id){
            $faAPI.shops.detailFpShopInformation({id:id}).then(function(jsdata){
                $scope.modal.shop_listDetail();
                console.log($scope.detail)
                var detailText = jsdata.dto;
                $scope.detail = test(detailText);
            })
        }
        //分享
        $scope.fxInformation = function(name,desc,img_url,id) {
            var linkurl;
            var type = true;

            if (img_url) {
                if (img_url.indexOf("http") > -1) {
                    img_url = img_url
                } else {
                    img_url = reqUrl + img_url + '?x-oss-process=image/resize,m_fill,h_100,w_100';
                }
            } else {
                img_url = 'http://lec.superfa.cn/upload/bann/20161208/1481164249317854085.png';
            }
            var shareData = {
                title: name,
                desc: desc,
                link: reqUrl + '/#/infromationNewListDetail/' + id + '/' + type + '?sphone=' + $scope.phone,
                imgUrl: img_url
            };
            if ($faPlatform.androidAPP) {
                document.addEventListener("deviceready", OnDeviceReady, false);

                function OnDeviceReady() {
                    cordova.exec(null, null, "MyPlugin", "toActivityShare", [shareData.title, shareData.desc, shareData.link, shareData.imgUrl]);
                }

                //window.shareCallBack();
            } else {
                actionShare(shareData.title, shareData.desc, shareData.link, shareData.imgUrl);
            }


        }



    })



    //详情查询
    .controller('InformationDetailCtrl',function($scope,$rootScope,$faAPI, $ionicPopup,$faModal,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate,$faPlatform,$state){
        $scope.baseUrl = reqUrl;
        var sphone = $stateParams.sphone;
        var id = $stateParams.id;
        $scope.type = $stateParams.type;
        $scope.sharephone = sphone;


        if(sphone) {
            $scope.phone = sphone;
        } else {
            $scope.phone = $faUser.info.mobile;
        }
        console.log($stateParams)
        var id = $stateParams.id;


        function test(data) {
            var str =JSON.stringify(data);
            var reg = new RegExp("&tp=webp","g");
            var a = str.replace(reg,"");
            var detail = $.parseJSON(a);
            return detail;
        }
        function getDetail(){
            $faAPI.shops.detailFpShopInformation({id:id}).then(function(jsdata){
                //alert(JSON.stringify(jsdata))
                //浏览量统计
                $faAPI.shops.countInformation({id:id}).then(function(redata){
                    // $scope.$apply()
                });

                var detailText = jsdata.dto;
                //$scope.detail = jsdata.dto;
                $scope.detail = test(detailText);

            });
        }
        getDetail();
        $scope.$on("$ionicView.enter", function () {
            //页面启动缓存时,其controller中不会反复执行，但会执行此监听-
            getshopUserInfo();

        });
        //删除关联
        $scope.delmsgpro = function(id){
            $faAPI.shops.deleteFpShopProjectInformationL({
                id:id
            }).then(function(redata){
                getshopUserInfo();
            });
        }

        $scope.toView = function (type, id) {

            if (type && id) {
                var url = '';

                if (type == '01') {
                    url = 'product.simu';

                } else if (type == '02' || type == '03') {
                    url = 'product.xtzgdetail';
                } else if (type == '07') {
                    url = 'product.xtzgdetail';

                }
                else if (type == '06') {
                    url = 'product.pevc';

                }

                $state.go(url, {id: id});
            } else {
                console.log('error,,');
            }

        };


        function getshopUserInfo(){
            $faAPI.shops.shopUserInfo({loginName: $scope.phone}).then(function(data){
                $scope.item = data.shopperUserInfoDto;
                $scope.user = data.dto;
                $scope.prodata = data.pro;
                console.log('nomad');
            })
        }
        getshopUserInfo();


         $scope.toShopHome = function(sphone) {
            $state.go('shopPreview', {sphone:sphone, isFromZixun:true})
        }


        //分享
        $scope.fxInformation = function(name,desc,img_url, flag,id){
            var linkurl;
            var type = true;
            if(flag == 1) {
                linkurl = reqUrl + '/#/infromationNewListDetail/' + id + '/' + type + '?sphone=' + $scope.phone
            } else if(flag == 3) {
                linkurl = reqUrl + '/#/infromationHotspotDetail/'+ id + '/' + type + '?sphone='+ $scope.phone
            }
            if(img_url){
                if(img_url.indexOf("http")>-1){
                    img_url=img_url
                }else{
                    img_url = reqUrl+ img_url+'?x-oss-process=image/resize,m_fill,h_100,w_100';
                }
            }else {
                img_url = 'http://lec.superfa.cn/upload/bann/20161208/1481164249317854085.png';
            }
            var shareData = {
                title: name,
                desc: desc,
                link: linkurl,
                /*link: $location.protocol() + '://' + $location.host() + '/#/shops/information?sphone=' + $scope.phone,*/
                imgUrl: img_url
            };
            console.log(name,desc,img_url,shareData.link)
            if($faPlatform.androidAPP){
                document.addEventListener("deviceready",OnDeviceReady, false);

                function OnDeviceReady()
                {
                    cordova.exec(null, null, "MyPlugin", "toActivityShare", [shareData.title,shareData.desc,shareData.link,shareData.imgUrl]);
                }
                //window.shareCallBack();
            }else{
                actionShare(shareData.title,shareData.desc,shareData.link,shareData.imgUrl);
            }
        }

    })

    //微信建群信息填写
    .controller('statisticsInfoCtrl',function($scope,$rootScope,$faAPI, $ionicPopup,$faModal,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate,$faPlatform,$state){
        $scope.data = {};
        $scope.save = function() {
            if(!$scope.data.wechatsName){
                $faPopup.alert({
                    title:'请输入微信群名称'
                });
                return false
            }
            if(!$scope.data.qName){
                $faPopup.alert({
                    title:'请输入发起人姓名'
                });
                return false
            }
            if(!$scope.data.qWechatId){
                $faPopup.alert({
                    title:'请输入发起人微信'
                });
                return false
            }
            if(!$scope.data.qMobile){
                $faPopup.alert({
                    title:'请输入发起人手机'
                });
                return false
            }else if (!/^1\d{10}$/.test($scope.data.qMobile)) {
                $faPopup.alert({
                    title: ' 手机号码格式错误'
                });
                return false
            }
            $faAPI.statistics.statisticsform($scope.data).then(function (json) {
                console.log(json)
                $faPopup.alert({
                    title:'保存成功'
                });
            })
        }

    })

//产品分享详情

    .controller('datamechHomeCtrl',function($scope,$rootScope,$ionicSideMenuDelegate ,$faAPI, $ionicPopup,$faModal,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate,$faPlatform,$state){
        $scope.n = 1;
        $scope.productName = $stateParams.productName;
        var param = $stateParams.param;
        $scope.name = $stateParams.name;
        var stime = $stateParams.tabTime;
        switch(stime){
            case '-6':
                $scope.n = 1;
                break;
            case '-29':
                $scope.n = 2;
                break;
            case '-179':
                $scope.n = 3;
                break;
            case '-365':
                $scope.n = 4;
                break;
            case '-1':
                $scope.n = 5;
                break;
        }
        console.log($scope.n)

        if(!$scope.name){
            $scope.name = '金策师';
        }
        $scope.id = $stateParams.id;
        console.log($stateParams)
        var iphone = $faUser.info.mobile;
        var sphone = $stateParams.sphone;
        if(!sphone){
            sphone = $faUser.info.mobile;
        }
        if( $scope.id){
            sphone = ''
        }
        console.log(sphone)
        $scope.dataTab = function (n,s) {
           $scope.n = n
            stime = s;
            console.log(stime)
            initData(sphone,$scope.id);
       }


        initData(sphone,$scope.id);
    function initData(uphone,id) {
        if(!sphone){
            sphone = $faUser.info.mobile;
        }
        if( $scope.id){
            sphone = ''
        }
        var dataObj = {
            productCode: param,
            pageSize: 500,
            getTimes: stime,
            uPhone: uphone,
            orgid: id
        }
        console.log(dataObj)
        $faAPI.shops.shareShopProductCount(dataObj).then(function (data) {
            var data = data;
            $scope.list = data.list;
            console.log($scope.list)
            console.log(stime)
        })
    }







        //机构树形菜单
        function initTheTree(){
            $faAPI.dataStatistics.getOrgTreeByPhone({//参数:  uPhone 登录人手机号
                uPhone:iphone
            }).then(function(json){
                console.log('机构树形菜单');
                console.log(json);
                $(document).ready(function(){
                    var _list  = json.list;
                    _list[0].open = true;//打开第一层节点
                    $.fn.zTree.init($("#treeDemo"), setting, json.list);
                    sleNode($scope.id);
                });
            });
            var setting = {
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback:{ //回调函数
                    /**
                     * event:鼠标事件
                     * treeId：树的容器id
                     * treeNode：当前点击的节点
                     */
                    beforeClick:function(treeId,treeNode,clickFlag){
                        console.log(treeNode);
                        //getData(treeNode.id);
                        //折线图及成交订单统计
                        //initlinedata('',$scope._times,treeNode.id);
                        //产品查看及分享汇总
                        //newPro('',$scope._times,100,treeNode.id);
                        $scope.name = treeNode.name;
                        if(treeNode.level == 0){
                            initData(sphone,'');

                        }else {
                            initData('',treeNode.id);
                            $scope.id = treeNode.id;
                        }
                        $scope.summModal.hide();
                    }
                }
            };
        }
        //initTheTree();
        $faModal('summModal', 'views/data/summaryModal.html', $scope, {
            initialize: function () {
                initTheTree();
            }
        });
        //选中指定节点
        function sleNode(pid){
            console.log(pid);
            var  zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
            var node = zTree_Menu.getNodeByParam("id",pid);
            //var nodes = zTree_Menu.getNodes();
            //if (nodes.length>0) {
            //    zTree_Menu.selectNode(nodes[4]);
            //}
            zTree_Menu.selectNode(node);//指定选中ID的节点
            //zTree_Menu.expandNode(node, true, true);//指定选中ID节点展开

        }
        //打开右侧菜单
        $scope.toggleRightSideMenu = function(){
            //$ionicSideMenuDelegate.toggleRight();
            $scope.modal.summModal();
        };
        //关闭右侧菜单
        $scope.closesmummary = function(){
            console.log('closesmummary');
            $scope.summModal.hide();
        };




    })











//产品查看详情
    .controller('dataProductlistCtrl',function($scope,$rootScope,$ionicSideMenuDelegate,$faAPI, $ionicPopup,$faModal,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate,$faPlatform,$state) {
        $scope.n = 1;
        console.log($stateParams)
        var param = $stateParams.param;
        var type = $stateParams.type;
        $scope.productName = $stateParams.productName;
        $scope.id = $stateParams.id;
        $scope.name = $stateParams.name;

        var stime = $stateParams.tabTime;
        switch(stime){
            case '-6':
                $scope.n = 1;
                break;
            case '-29':
                $scope.n = 2;
                break;
            case '-179':
                $scope.n = 3;
                break;
            case '-365':
                $scope.n = 4;
                break;
            case '-1':
                $scope.n = 5;
                break;
        }
        if(!$scope.name){
            $scope.name = '金策师';
        }
        var sphone = $stateParams.sphone;
        var iphone = $faUser.info.mobile;
        if(!sphone){
            sphone = $faUser.info.mobile;
        }
        if($scope.id){
            sphone = ''
        }

        $scope.dataTab = function (n,s) {
            $scope.n = n;
            stime = s;
            initData(sphone,$scope.id)
        }
        initData(sphone,$scope.id)
    function initData(uphone,id) {
        var dataObj = {
            pageNo: 1,
            pageSize: 500,
            getTimes: stime,
            shopId: sphone,
            param: param,
            type: type,
            orgid:id,
            uPhone:uphone
        }
        console.log(dataObj)
        $faAPI.shops.shopProductSeeDetail(dataObj).then(function (data) {
            $scope.list = data.list;
            console.log(data)
        })
    }







        //机构树形菜单
        function initTheTree(){
            $faAPI.dataStatistics.getOrgTreeByPhone({//参数:  uPhone 登录人手机号
                uPhone:iphone
            }).then(function(json){
                console.log('机构树形菜单');
                console.log(json);
                $(document).ready(function(){
                    var _list  = json.list;
                    _list[0].open = true;//打开第一层节点
                    $.fn.zTree.init($("#treeDemo"), setting, json.list);
                    sleNode($scope.id);
                });
            });
            var setting = {
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback:{ //回调函数
                    /**
                     * event:鼠标事件
                     * treeId：树的容器id
                     * treeNode：当前点击的节点
                     */
                    beforeClick:function(treeId,treeNode,clickFlag){
                        console.log(treeNode);
                        //getData(treeNode.id);
                        //折线图及成交订单统计
                        //initlinedata('',$scope._times,treeNode.id);
                        //产品查看及分享汇总
                        //newPro('',$scope._times,100,treeNode.id);
                        $scope.name = treeNode.name;
                        if(treeNode.level == 0){
                            initData(sphone,'');

                        }else {
                            initData('',treeNode.id);
                            $scope.id = treeNode.id;
                        }
                        $scope.summModal.hide();
                    }
                }
            };
        }
        //initTheTree();
        $faModal('summModal', 'views/data/summaryModal.html', $scope, {
            initialize: function () {
                initTheTree();
            }
        });
        function sleNode(pid){
            console.log(pid);
            var  zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
            var node = zTree_Menu.getNodeByParam("id",pid);
            //var nodes = zTree_Menu.getNodes();
            //if (nodes.length>0) {
            //    zTree_Menu.selectNode(nodes[4]);
            //}
            zTree_Menu.selectNode(node);//指定选中ID的节点
            //zTree_Menu.expandNode(node, true, true);//指定选中ID节点展开

        }
        //打开右侧菜单
        $scope.toggleRightSideMenu = function(){
            //$ionicSideMenuDelegate.toggleRight();

            $scope.modal.summModal();
        };
        //关闭右侧菜单
        $scope.closesmummary = function(){
            console.log('closesmummary');
            $scope.summModal.hide();
        };










    })

//订单详情
    .controller('dataOrderDetailsCtrl',function($scope,$rootScope,$ionicSideMenuDelegate ,$faAPI, $ionicPopup,$faModal,$faUser,$faUtil,$stateParams,$faPopup,$interval, $ionicScrollDelegate,$ionicSlideBoxDelegate,$faPlatform,$state){
        console.log($stateParams,'传过来的参数')
        var sphone = $stateParams.sphone;
        $scope.name = $stateParams.name;
        var stime = $stateParams.tabTime;
        switch(stime){
            case '-6':
                $scope.n = 1;
                break;
            case '-29':
                $scope.n = 2;
                break;
            case '-179':
                $scope.n = 3;
                break;
            case '-365':
                $scope.n = 4;
                break;
            case '-1':
                $scope.n = 5;
                break;
        }
        console.log($scope.n)
        if(!$scope.name){
            $scope.name = '金策师';
        }
        $scope.id = $stateParams.id;
        $scope.amountType = $stateParams.amountType;
        var mySwiper = null;
        var iphone = $faUser.info.mobile;
        console.log(iphone)
        if(!sphone){
            sphone = $faUser.info.mobile;
        }
        if($scope.id){
            sphone = ''
        }

        $scope.dataTab = function (n,s) {
            $scope.n = n;
            stime = s;
            initData(sphone,$scope.id)
        }

        $scope.dataTab($scope.n,stime)





        function initData(uphone,id){
            if(!sphone){
                sphone = $faUser.info.mobile;
            }
            if($scope.id){
                sphone = ''
            }
            var dataObj = {
                amountType:$scope.amountType,
                uPhone:uphone,
                times:stime,
                orgid:id
            }
console.log(dataObj)

            $faAPI.shops.queryDoneByAmount(dataObj).then(function (data) {
                console.log(data)
                var Detail = data;
                $scope.orderList = data.orderlist;

                setTimeout(function(){
                    console.log("初始化")
                    mySwiper = new Swiper ('.swiper-container', {
                        direction: 'vertical',
                        initalSlide: 0

                        })
                }, 100)

                if(mySwiper) {
                    mySwiper.slideTo(0, 100, false);
                    mySwiper.destroy(true, false);
                }
            })

        }
        initData(sphone,$scope.id);


        //机构树形菜单
        function initTheTree(){
            console.log('机构树形菜单');
            console.log(iphone);
            $faAPI.dataStatistics.getOrgTreeByPhone({//参数:  uPhone 登录人手机号
                uPhone:iphone
            }).then(function(json){
                console.log('机构树形菜单');
                console.log(json);
                $(document).ready(function(){
                    var _list  = json.list;
                    _list[0].open = true;//打开第一层节点
                    $.fn.zTree.init($("#treeDemo"), setting, json.list);
                    sleNode($scope.id);
                });
            });
            var setting = {
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback:{ //回调函数
                    /**
                     * event:鼠标事件
                     * treeId：树的容器id
                     * treeNode：当前点击的节点
                     */
                    beforeClick:function(treeId,treeNode,clickFlag){
                        console.log(treeNode);
                        //getData(treeNode.id);
                        //折线图及成交订单统计
                        //initlinedata('',$scope._times,treeNode.id);
                        //产品查看及分享汇总
                        //newPro('',$scope._times,100,treeNode.id);
                        $scope.name = treeNode.name;
                        if(treeNode.level == 0){
                            initData(sphone,'');

                        }else {
                            initData('',treeNode.id);
                            $scope.id = treeNode.id;
                        }
                        $scope.summModal.hide();
                    }
                }
            };
        }
        //initTheTree();
        $faModal('summModal', 'views/data/summaryModal.html', $scope, {
            initialize: function () {
                initTheTree();
            }
        });
        function sleNode(pid){
            console.log(pid);
            var  zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
            var node = zTree_Menu.getNodeByParam("id",pid);
            //var nodes = zTree_Menu.getNodes();
            //if (nodes.length>0) {
            //    zTree_Menu.selectNode(nodes[4]);
            //}
            zTree_Menu.selectNode(node);//指定选中ID的节点
            //zTree_Menu.expandNode(node, true, true);//指定选中ID节点展开

        }
        //打开右侧菜单
        $scope.toggleRightSideMenu = function(){
            //$ionicSideMenuDelegate.toggleRight();
            $scope.modal.summModal();
        };
        //关闭右侧菜单
        $scope.closesmummary = function(){
            console.log('closesmummary');
            $scope.summModal.hide();
        };


    })
